Lazy Fibonacci Sequence
Ah, the ubiquitous example of recursive functions. Well, this is not your traditional fibonacci sequence exercise.
We all know that the fibonacci sequence is defined as:
(fib 0) ;=> 1
(fib 1) ;=> 1
(fib n) ;=> (+ (fib (dec n)) (fib (dec (dec n))))
And we know we could generate it forward, one element at a time, in a lazy fashion. That is your first task!
(fib-seq) ;=> (1 1 2 3 5 8 13 ....) lazily generated because it's infinite
But we could parameterize some of the things in the definition, like the first and second elements (both 1
s), and the operation to apply (+
). We should be able to pass them as arguments:
(fib-seq + 1 1) ;=> (1 1 2 3 5 8 13 ....)
That's your second task.
Your third task is more interesting: We don't have to limit ourselves to addition. In fact, we should be able to use any function that takes two arguments of type T and returns a value of T (closure property). Your task is to generate the first 10 elements of the sequence (use take
) for each of these combinations:
(fib-seq str "X" "O")
(fib-seq * 1 1)
(fib-seq * 1 2)
(fib-seq * 1 -1)
(fib-seq vector [] [])
Thanks to this site for the problem idea, where it is rated Expert in Java. The problem has been modified.
Please submit your solutions as comments on this gist.
To subscribe: https://ericnormand.me/newsletter
with
FibIter
being