The code that Danny wrote to create fib-stream works great with his peek-fibs function, but I really don't understand stream-first.<div><br></div><div>I wrote:</div><div><br></div><div><div>; function to use the fib-stream to generate a list of all fibs < n</div>
<div>(define (fib-stream-less-than-n n)</div><div> (let ([fib-val (stream-first fib-stream)])</div><div> (if (>= fib-val n) '() (cons fib-val (fib-less-than-n n)))))</div><div><br></div><div>I get:</div><div><br>
</div><div><div>(fib-stream-less-than-n 500)</div><div>'(0 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377)</div></div><div><br></div><div>Note the two leading 0s. This perplexed me, until I read about stream-first then I realized that I really didn't understand anything. I believe the function above should return</div>
<div>'(0 0 0 0 0 0 0 ...)</div><div><br></div><div>Can someone tell me what is going on?</div><div><br></div><div>Thanks,</div><div>-Joe</div><br><div class="gmail_quote">On Mon, Feb 13, 2012 at 9:10 PM, Danny Yoo <span dir="ltr"><<a href="mailto:dyoo@cs.wpi.edu">dyoo@cs.wpi.edu</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="im">On Mon, Feb 13, 2012 at 11:52 PM, Joe Gilray <<a href="mailto:jgilray@gmail.com">jgilray@gmail.com</a>> wrote:<br>
> Warning: extreme newbie question ahead.<br>
><br>
> I wrote the following fibonacci function:<br>
><br>
> ; function that returns the next fibonacci number each time it is called<br>
> ; invoke as (fib)<br>
> (define fib<br>
> (let ([n0 -1] [n1 1])<br>
> (lambda ()<br>
> (let ([next (+ n0 n1)])<br>
> (set! n0 n1)<br>
> (set! n1 next))<br>
> n1)))<br>
<br>
<br>
</div>One thing you can do is turn fib into a "sequence", and then from a<br>
sequence into a stream that knows how to remember its previous values.<br>
<br>
Here's what it might look like:<br>
<br>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<br>
#lang racket<br>
(require racket/sequence)<br>
<div class="im"><br>
(define fib<br>
(let ([n0 -1] [n1 1])<br>
(lambda ()<br>
(let ([next (+ n0 n1)])<br>
(set! n0 n1)<br>
(set! n1 next))<br>
n1)))<br>
<br>
</div>(define fib-stream<br>
;; Here's a sequence of the function:<br>
(let ([fib-sequence (in-producer fib 'donttellmecauseithurts)])<br>
<br>
;; Let's wrap it and turn it into a stream that remembers...<br>
(sequence->stream fib-sequence)))<br>
<br>
<br>
;; Ok, we've got a stream. Let's look at its first few elements.<br>
(define (peek-fibs n)<br>
(for ([elt fib-stream]<br>
[i (in-range n)])<br>
(displayln elt)))<br>
<br>
(peek-fibs 10)<br>
(printf "-----\n")<br>
(peek-fibs 20)<br>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<br>
</blockquote></div><br></div>