What about something like (untested, assumption that false, and not undef is a flag for end of data, and that the tree is well-formed (no hashref, for example)):
sub genIterator { my $tree = shift; my @stack = ( [ 0, $tree ], 0 ); return sub { my $work = shift( @stack ); while ( ref( $work ) ) { my $index = $work->[0]; my $worktree = $work->[1]; if ( $index >= scalar( @{$worktree} ) ) { # Update 3 $work = shift( @stack ); next; } elsif ( ! ref( $worktree->[$index] ) ) { unshift( @stack, [ $index+1, $worktree ] ); return $worktree->[$index]; } else { unshift( @stack, [ $index+1, $worktree ] ); $work = [ 0, $worktree->[$index] ]; next; } } return; # empty stack } }
Test Code:
my @data = [ [ 0 ], 1, 2, [ 3, 4, 5 ], 6, [ 7, 8, [ 9, 10 ], [ 11, [ 1 +2 ], 13 ], ], 14 ]; my $it = genIterator( \@data ); use DDP; p @data; while (defined( my $x = $it->() )) { say $x; } __END__ [ [0] [ [0] [ [0] 0 ], [1] 1, [2] 2, [3] [ [0] 3, [1] 4, [2] 5 ], [4] 6, [5] [ [0] 7, [1] 8, [2] [ [0] 9, [1] 10 ], [3] [ [0] 11, [1] [ [0] 12 ], [2] 13 ] ], [6] 14 ] ] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Update: No longer need to assume that '0' is an invalid element, but the use of the iterator needs to be adjusted.
Update 2: Compared to Eily's solution, mine is iterative (non recursive), while Eily's is recursive.
UPdate 3: changed '>' to '>=' after testing, added test code.
--MidLifeXis
In reply to Re: An iterator for (not "iterating") a recursive data structure.
by MidLifeXis
in thread An iterator for (not "iterating") a recursive data structure.
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |