Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try this, implemented using lazy code by means of <a href="http://docs.racket-lang.org/reference/Delayed_Evaluation.html" rel="nofollow">delayed evaluation</a>:</p> <pre><code>(define (each-fib fn) (letrec ((next (lambda (a b) (fn a) (delay (next b (+ a b)))))) (next 0 1))) (define (take-n-fibs n fn) (let loop ((i n) (promise (each-fib fn))) (when (positive? i) (loop (sub1 i) (force promise))))) </code></pre> <p>As has been mentioned, <code>each-fib</code> can be further simplified by using a <a href="http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_sec_11.16" rel="nofollow">named <code>let</code></a>:</p> <pre><code>(define (each-fib fn) (let next ((a 0) (b 1)) (fn a) (delay (next b (+ a b))))) </code></pre> <p>Either way, it was necessary to modify <code>each-fib</code> a little for using the <code>delay</code> primitive, which creates a promise:</p> <blockquote> <p>A <em>promise</em> encapsulates an expression to be evaluated on demand via <code>force</code>. After a promise has been <code>force</code>d, every later force of the promise produces the same result.</p> </blockquote> <p>I can't think of a way to stop the original (unmodified) procedure from iterating indefinitely. But with the above change in place, <code>take-n-fibs</code> can keep forcing the lazy evaluation of as many values as needed, and no more.</p> <p>Also, <code>take-n-fibs</code> now receives a function for printing or processing each value in turn, use it like this:</p> <pre><code>(take-n-fibs 10 (lambda (n) (printf "~a " n))) &gt; 0 1 1 2 3 5 8 13 21 34 55 </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