Skip to content

Instantly share code, notes, and snippets.

@stevan
Created April 3, 2013 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevan/f511018440e6a2f52830 to your computer and use it in GitHub Desktop.
Save stevan/f511018440e6a2f52830 to your computer and use it in GitHub Desktop.
class Tree {
has $!node;
has $!parent;
has @!children = [];
BUILD ($node, @children?) {
$!node = $node;
if (@children) {
@!children = @children;
self._fix_parent;
}
}
method node { $!node }
method parent ($parent?) {
if ($parent) { $!parent = $parent; }
$!parent
}
method depth { $!parent ? $!parent.depth + 1 : 0 }
method traverse (&f) {
&f.(self);
@!children.each(-> ($c) {
$c.traverse(&f)
})
}
method _fix_parent {
@!children.each(-> ($c) { $c.parent(self) })
}
}
my $t = ^Tree.new("0.0", [
^Tree.new("1.0", [
^Tree.new("1.1"),
^Tree.new("1.2", [
^Tree.new("1.2.1"),
^Tree.new("1.2.2"),
])
]),
^Tree.new("2.0", [
^Tree.new("2.1", [
^Tree.new("2.1.1", [
^Tree.new("2.1.1.1"),
]),
^Tree.new("2.1.2", [
^Tree.new("2.1.2.1"),
^Tree.new("2.1.2.2"),
])
])
]),
^Tree.new("3.0"),
]);
$t.traverse(-> ($c) {
say( (".." x $c.depth), $c.node )
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment