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

Re^2: Question about recursively generated iterators

by ikegami (Pope)
on Sep 21, 2007 at 16:48 UTC ( #640397=note: print w/ replies, xml ) Need Help??


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

This method can be used when a function has a loop, since loops can be implemented using recursion. This is great because it facilitates making iterators from functions where the call to the visitor is not at the end and from functions with multiple calls to the visitor.

For example, let's create a fibonacci generator. A simple implementation is:

sub fibonacci { my ($visitor) = @_; my ($i, $j) = (0, 1); $visitor->() for $i; for (;;) { $visitor->() for $j; ($i, $j) = ($j, $i+$j); } }

Replace the loop with recursion.

sub fibonacci { my ($visitor) = @_; my ($i, $j) = (0, 1); $visitor->() for $i; _fibonacci($i, $j); } sub _fibonacci { my ($visitor, $i, $j) = @_; $visitor->() for $j; _fibonacci($j, $i+$j); }

Convert for make_iter.

sub fibonacci { my ($i, $j) = (0, 1); return ( \$i, sub { _fibonacci($i, $j) } ); } sub _fibonacci { my ($i, $j) = @_; return ( \$j, sub { _fibonacci($j, $i+$j) } ); }

Try it out

{ my $iter = make_iter(\&fibonacci); for (0..15) { my ($n) = $iter->() or last; print("$n "); } print("\n"); }
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610


Comment on Re^2: Question about recursively generated iterators
Select or Download Code
Replies are listed 'Best First'.
Re^3: Question about recursively generated iterators
by perlfan (Curate) on Sep 21, 2007 at 19:32 UTC
    Very much appreciated, ikegami! This is very helpful.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (16)
As of 2015-07-28 16:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (258 votes), past polls