Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^5: Question about recursively generated iterators

by Limbic~Region (Chancellor)
on Sep 22, 2007 at 00:55 UTC ( [id://640462]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Question about recursively generated iterators
in thread Question about recursively generated iterators

perlfan,
Doing a DFS as an iterator is pretty simple. If this code example isn't sufficient, let me know.
#!/usr/bin/perl use strict; use warnings; { my %seen; my %tree = ( A => ['B', 'C'], B => ['D', 'E'], C => ['F', 'G'], E => ['H', 'I'], G => ['J', 'K'], H => ['L', 'M', 'N'], I => ['O', 'P'], K => ['Q'], ); sub get_root { 'A' } sub get_children { my ($node) = @_; return $tree{$node} ? @{$tree{$node}} : (); } sub visited { my ($node, $val) = @_; return $seen{$node} = $val if defined $val; return $seen{$node}; } } sub gen_tree_iter { my @nodes = get_root(); return sub { { my $node = shift @nodes; return undef if ! defined $node; redo if visited($node); visited($node => 1); unshift @nodes, get_children($node); return $node; } }; } my $iter = gen_tree_iter(); while (my $node = $iter->()) { print "Visiting $node\n"; }

Cheers - L~R

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://640462]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-04-25 07:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found