Created
March 17, 2015 18:02
-
-
Save zoul/f5aebac79406d96296a7 to your computer and use it in GitHub Desktop.
Building an immutable tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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