[racket] Making a Racket function "recallable"

From: Joe Gilray (jgilray at gmail.com)
Date: Mon Feb 13 23:52:14 EST 2012

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))

This function works, but is not "recallable" (is there a better word?).  In
other words I cannot do the following:

(define f1 fib)
(define f2 fib)
(f1) (f1) (f2) ...

and have f1 and f2 be separate fibonacci lists.  Somehow n0 and n1 have to
be instance-specific and right now they are not.

Because of this limitation the following useful looking function only works
the first time it is called:

; function that returns a list of fibonacci numbers less than the passed
(define (fib-less-than-n n)
  (let ([fib-val (fib)])
    (if (>= fib-val n) '() (cons fib-val (fib-less-than-n n)))))

Any help appreciated.  Any tips about stupidities in the code above welcome

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120213/a363895e/attachment.html>

Posted on the users mailing list.