Skip to content

Instantly share code, notes, and snippets.

@polux
Created December 18, 2013 22:08
Show Gist options
  • Save polux/8030692 to your computer and use it in GitHub Desktop.
Save polux/8030692 to your computer and use it in GitHub Desktop.
Staged contains method for binary trees
class Node {
final val;
final left;
final right;
Node(this.val, this.left, this.right);
insert(n) =>
n.lt(this.val)
? new Node(this.val, this.left.insert(n), this.right)
: new Node(this.val, this.left, this.right.insert(n));
freeze() => new Node(((v) => <v>)(this.val),
this.left.freeze(),
this.right.freeze());
contains(e) =>
<(~e).eq(~this.val)
? true
: ((~e).lt(~this.val)
? ~this.left.contains(e)
: ~this.right.contains(e))>;
}
class Tip {
Tip();
insert(n) => new Node(n, new Tip(), new Tip());
freeze() => new Tip();
contains(e) => <false>;
}
class Demo {
Demo();
in12345() {
final tree = new Tip().insert(4).insert(2).insert(1).insert(3).insert(5);
return run(<(e) => ~tree.freeze().contains(<e>)>);
}
}
main() {
print(new Demo().in12345());
print(new Demo().in12345()(3));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment