[racket] Making a Racket function "recallable"
On Feb 14, 2012, at 12:51 AM, Erik Silkensen wrote:
> Instead of calling fib-less-than-n recursively, you could add a loop inside, for example something like,
>
> (define (fib-less-than-n n)
> (define fib (mk-fib))
> (let loop ([vs '()])
> (let ([fib-val (fib)])
> (if (>= fib-val n)
> (reverse vs)
> (loop (cons fib-val vs))))))
Let's generalize and abstract this to "take-while":
(define (take-while generator test?)
(reverse
(let loop [[vs '()]]
(let [[value (generator)]]
(if (test? value)
(loop (cons value vs))
vs)))))
(define (fib-less-than-n n)
(take-while (mk-fib) (lambda (value) (< value n))))
[I haven't typed this code in and tested it, so there may be typos.]
Stephen Bloch
sbloch at adelphi.edu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120214/c414fba1/attachment.html>