aboutsummaryrefslogtreecommitdiff
path: root/challenge-113/james-smith/perl/Tree.pm
blob: de215abb4639d5ca77af7647b46c562ca2856023 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package Tree;

## The tree is stored in an array ref
# The first element is the value of the node
# The remainder of the array are child sub-trees
#
# Methods:
#  ->add_child( $child_tree )
#  ->flatten                  -- flatten list to array.
#

sub new {
  my $class = shift;
  my $value = shift;
  my $self = [ $value ];
  bless $self, $class;
}

sub add_child {
  my( $self,$child ) = @_;
  push @{$self}, $child;
  return $self;
}

sub walk {
  my( $self, $fn, $data, $t ) = @_;
  my ($v,@sub) = @{$self};
  $t = $fn->( $self, $data, $t );
  $_->walk( $fn, $data, $t ) foreach @sub;
  return;
}

sub flatten {
  my $self = shift;
  my ($v,@sub) = @{$self};
  return ( $v, map { $_->flatten } @sub );
}

1;