I’m trying to solve this problem in a pure-functional way, without using set!.
I’ve written a function that calls a given lambda for each number in the fibonacci series, forever.
(define (each-fib fn)
(letrec
((next (lambda (a b)
(fn a)
(next b (+ a b)))))
(next 0 1)))
I think this is as succinct as it can be, but if I can shorten this, please enlighten me 🙂
With a definition like the above, is it possible to write another function that takes the first n numbers from the fibonacci series and gives me a list back, but without using variable mutation to track the state (which I understand is not really functional).
The function signature doesn’t need to be the same as the following… any approach that will utilize each-fib without using set! is fine.
(take-n-fibs 7) ; (0 1 1 2 3 5 8)
I’m guessing there’s some sort of continuations + currying trick I can use, but I keep coming back to wanting to use set!, which is what I’m trying to avoid (purely for learning purposes/shifting my thinking to purely functional).
Try this, implemented using lazy code by means of delayed evaluation:
As has been mentioned,
each-fibcan be further simplified by using a namedlet:Either way, it was necessary to modify
each-fiba little for using thedelayprimitive, which creates a promise:I can’t think of a way to stop the original (unmodified) procedure from iterating indefinitely. But with the above change in place,
take-n-fibscan keep forcing the lazy evaluation of as many values as needed, and no more.Also,
take-n-fibsnow receives a function for printing or processing each value in turn, use it like this: