Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For an even more flexible solution than Python's generators, I have written the module <a href="http://search.cpan.org/perldoc?List::Gen" rel="noreferrer">List::Gen</a> on CPAN which provides random access lazy generator arrays:</p> <pre><code>use List::Gen; my $fib; $fib = cache gen {$_ &lt; 2 ? $_ : $$fib[$_ - 1] + $$fib[$_ - 2]}; say "@$fib[0 .. 15]"; # 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 </code></pre> <p>Since generators pretend to be arrays, they can mix seamlessly with normal perl code. There is also an object oriented approach:</p> <pre><code>my $fib; $fib = cache gen {$_ &lt; 2 ? $_ : $fib-&gt;get($_ - 1) + $fib-&gt;get($_ - 2)}; say join ' ' =&gt; $fib-&gt;slice(0 .. 15); </code></pre> <p>In each case, the generator is lazy, calculating nothing upon creation, and then calculating only those values required to satisfy the slices. The recursive definition of the Fibonacci sequence calls itself many times, so the <code>cache</code> function is used to make sure each value is only calculated once. </p> <p>You can also use generators as iterators:</p> <pre><code>while (my $num = $fib-&gt;next) { last if $num &gt; 10**15; print "$_\n"; } </code></pre> <p><code>$fib-&gt;next</code> can also be written <code>$fib-&gt;()</code>. Since the generator is still random access, you can <code>$fib-&gt;reset()</code> or <code>$fib-&gt;index = 10;</code></p> <p>Let me know if you have any questions.</p> <p>Update:</p> <p>I have released a new version of the module (0.80) that makes it easier to use iterative algorithms in generators. Here is an example that closely mirrors the OP's example:</p> <pre><code>use List::Gen '*'; sub fibonacci { my $limit = 10**shift; my ($x, $y) = (0, 1); While {$_ &lt; $limit} gather { ($x, $y) = ($y, take($x) + $y) } } say for @{fibonacci 15}; </code></pre> <p>if you <code>use bigint;</code> before or at the top of the sub, you can of course:</p> <pre><code>say for @{fibonacci 400}; # or more </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload