Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??

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

In reply to Re^2: Question about recursively generated iterators by ikegami
in thread Question about recursively generated iterators by perlfan

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others drinking their drinks and smoking their pipes about the Monastery: (8)
    As of 2015-01-31 22:37 GMT
    Find Nodes?
      Voting Booth?

      My top resolution in 2015 is:

      Results (261 votes), past polls