Skip to content

Instantly share code, notes, and snippets.

@lucaswerkmeister
Created March 18, 2014 21:35
Show Gist options
  • Save lucaswerkmeister/9630244 to your computer and use it in GitHub Desktop.
Save lucaswerkmeister/9630244 to your computer and use it in GitHub Desktop.
A Tree in Ceylon, by @yellowant’s suggestion
import ceylon.collection { MutableList, LinkedList }
shared interface Tree<Element>
satisfies {Element+}
given Element satisfies Object {
shared formal {Tree<Element>|Element+} children;
shared actual Iterator<Element> iterator() {
object iterator satisfies Iterator<Element> {
MutableList<Iterator<Tree<Element>|Element>> stack
= LinkedList<Iterator<Tree<Element>|Element>> { children.iterator() };
shared actual Element|Finished next() {
while (exists it = stack.last) {
value item = it.next();
if (is Tree<Element> item) {
stack.add(item.iterator());
continue;
} else if (is Element item) {
return item;
} else {
assert (is Finished item);
stack.deleteLast();
continue;
}
}
return finished;
}
}
return iterator;
}
}
shared interface Hierarchy<Sub, Element>
satisfies Tree<Element>
given Element satisfies Object
given Sub satisfies Tree<Element> {
shared actual formal {Sub+} children;
}
shared interface FlatTree<Element>
satisfies Tree<Element>
given Element satisfies Object {
shared actual [Element] children => [element];
shared formal Element element;
}
shared class TreeImpl<Element>(children)
satisfies Tree<Element>
given Element satisfies Object {
shared actual {Tree<Element>|Element+} children;
}
shared class HierarchyImpl<Sub, Element>(children)
satisfies Hierarchy<Sub, Element>
given Element satisfies Object
given Sub satisfies Tree<Element> {
shared actual {Sub+} children;
}
shared class FlatTreeImpl<Element>(element)
satisfies FlatTree<Element>
given Element satisfies Object {
shared actual Element element;
}
shared abstract class Presence(string) of available|away|doNotDisturb { shared actual String string; }
shared object available extends Presence("Available") {}
shared object away extends Presence("Away") {}
shared object doNotDisturb extends Presence("Do not disturb") {}
shared class Entry({Presence+} presences) extends HierarchyImpl<FlatTree<Presence>, Presence>(presences.map(FlatTreeImpl<Presence>)) {}
shared class Group({Entry+} entries) => HierarchyImpl<Entry, Presence>(entries);
shared class Roster({Group+} groups) => HierarchyImpl<Group, Presence>(groups);
void run() {
Roster roster = Roster {
Group {
Entry {
away
},
Entry {
available
}
},
Group {
Entry {
available
}
}
};
Group group = roster.children.first;
Entry entry = group.children.first;
Presence presence = entry.first;
assert (presence == roster.first);
print(roster);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment