Skip to content

Instantly share code, notes, and snippets.

@zoul
Created March 17, 2015 18:02
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 zoul/f5aebac79406d96296a7 to your computer and use it in GitHub Desktop.
Save zoul/f5aebac79406d96296a7 to your computer and use it in GitHub Desktop.
Building an immutable tree
#!/usr/bin/env perl
use v5.14;
use strict;
use warnings;
use Data::Dump 'pp';
{
package Node;
use Mouse;
has 'tag' => (isa => 'Str', is => 'ro');
has 'children' => (isa => 'ArrayRef[Node]', is => 'ro', writer => '_set_children');
has 'parent' => (isa => 'Maybe[Node]', is => 'ro');
sub build_tree {
my ($class, $tag, $rest, $parent) = @_;
my $node = Node->new(tag => $tag, parent => $parent);
my @children;
while (my ($k, $v) = each %$rest) {
push @children, $class->build_tree($k, $v, $node);
}
$node->_set_children(\@children);
return $node;
}
}
pp(Node->build_tree(
a => {
b => {
c => {},
},
}
));
__END__
do {
my $a = bless({
children => [
bless({
children => [
bless({ children => [], parent => 'fix', tag => "c" }, "Node"),
],
parent => 'fix',
tag => "b",
}, "Node"),
],
parent => undef,
tag => "a",
}, "Node");
$a->{children}[0]{children}[0]{parent} = $a->{children}[0];
$a->{children}[0]{parent} = $a;
$a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment