[racket] Making a Racket function "recallable"

From: Joe Gilray (jgilray at gmail.com)
Date: Wed Feb 15 03:10:05 EST 2012

The code that Danny wrote to create fib-stream works great with his
peek-fibs function, but I really don't understand stream-first.

I wrote:

; function to use the fib-stream to generate a list of all fibs < n
(define (fib-stream-less-than-n n)
  (let ([fib-val (stream-first fib-stream)])
    (if (>= fib-val n) '() (cons fib-val (fib-less-than-n n)))))

I get:

(fib-stream-less-than-n 500)
'(0 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377)

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
'(0 0 0 0 0 0 0 ...)

Can someone tell me what is going on?

Thanks,
-Joe

On Mon, Feb 13, 2012 at 9:10 PM, Danny Yoo <dyoo at cs.wpi.edu> wrote:

> On Mon, Feb 13, 2012 at 11:52 PM, Joe Gilray <jgilray at gmail.com> wrote:
> > Warning: extreme newbie question ahead.
> >
> > I wrote the following fibonacci function:
> >
> > ; function that returns the next fibonacci number each time it is called
> > ; invoke as (fib)
> > (define fib
> >   (let ([n0 -1] [n1 1])
> >     (lambda ()
> >       (let ([next (+ n0 n1)])
> >         (set! n0 n1)
> >         (set! n1 next))
> >       n1)))
>
>
> One thing you can do is turn fib into a "sequence", and then from a
> sequence into a stream that knows how to remember its previous values.
>
> Here's what it might look like:
>
> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> #lang racket
> (require racket/sequence)
>
> (define fib
>  (let ([n0 -1] [n1 1])
>    (lambda ()
>      (let ([next (+ n0 n1)])
>        (set! n0 n1)
>        (set! n1 next))
>      n1)))
>
> (define fib-stream
>  ;; Here's a sequence of the function:
>  (let ([fib-sequence (in-producer fib 'donttellmecauseithurts)])
>
>    ;; Let's wrap it and turn it into a stream that remembers...
>    (sequence->stream fib-sequence)))
>
>
> ;; Ok, we've got a stream.  Let's look at its first few elements.
> (define (peek-fibs n)
>  (for ([elt fib-stream]
>        [i (in-range n)])
>    (displayln elt)))
>
> (peek-fibs 10)
> (printf "-----\n")
> (peek-fibs 20)
> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120215/4a96ac69/attachment.html>

Posted on the users mailing list.