[racket] Making a Racket function "recallable"

From: Stephen Bloch (bloch at adelphi.edu)
Date: Tue Feb 14 06:35:24 EST 2012

On Feb 14, 2012, at 12:18 AM, Erik Silkensen wrote:

> Another option is you could turn change your fib function to be 'mk-fib' that returns a new instance of the fib function each time it's called:
> 
> (define (mk-fib)
>  (let ([n0 -1] [n1 1])
>    (lambda ()
>      (let ([next (+ n0 n1)])
>        (set! n0 n1)
>        (set! n1 next))
>      n1)))

I frequently assign this sort of thing near the end of a first programming course.  First, I have students write a function "next" which returns how many times it's been called.  Then "next-color", which on successive calls returns "red", "orange", "yellow", "green", "blue", "violet", #f, #f, ...  Then "make-lister", which on input (list "red" "orange" "yellow" "green" "blue" "violet") returns a function acting like "next-color".

One suggestion: I would have mk-fib take in two parameters specifying the initial values of fib, rather than always making them -1 and 1.

Stephen Bloch
sbloch at adelphi.edu



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

Posted on the users mailing list.