Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^3: Question about recursively generated iterators

by Limbic~Region (Chancellor)
on Sep 21, 2007 at 17:33 UTC ( [id://640409]=note: print w/replies, xml ) Need Help??


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

perlfan,
Your stuff actually got me started down this dark and scary road :)

I am truly flattered. I can show you examples of both DFS and BFS iterators but they are not ones that I converted from a recursive algorithm. I almost never think of problems in terms of recursion. Probably why Haskell still eludes me.

Don't hesitate to /msg me with questions about something I have written, if you would like some examples, or if you would like me to write up a tutorial on something (assuming I am capable).

Cheers - L~R

  • Comment on Re^3: Question about recursively generated iterators

Replies are listed 'Best First'.
Re^4: Question about recursively generated iterators
by perlfan (Vicar) on Sep 21, 2007 at 19:31 UTC
    I am not stuck on doing this recursively - a DFS iterator example or tutorial would be killer. I'll send you a msg, too. Thanks!
      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

      perlfan,
      I wrote another version of the DFS iterator that was more memory efficient at the sacrifice of speed since I wasn't sure which was more important to you. The most items this version will ever have on the stack/queue is the max depth of the tree.

      Please let me know if this requires explanation as it is not as clear as the original.

      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://640409]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-19 14:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found