I would like to create a function that returns a lazily extended infinite sequence of Fibonacci numbers.
Now I can make my sequence available in the top-level namespace as follows:
(def fibonacci-numbers (lazy-cat [0 1] (map + fibonacci-numbers (rest fibonacci-numbers))))
However, this means that if I start consuming a lot of them, I will lose control over garbage collection.
I want to do something like:
(defn fibonacci-numbers-fn [] (lazy-cat [0 1] (map + (fibonacci-numbers-fn) (rest (fibonacci-numbers-fn)))))
This obviously won't work, because I will create O (2 ^ n) sequences. I think I'm asking how to create a self-referential lazy sequence in a function namespace. What should I do?
EDIT: Although I like the popular solution posted by amalloy and found all over the Internet defn fibs [] (map first (iterate (fn [[ab]] [b (+ ab)]) [0 1]))) , I'm interested in the version similar to the canonical Haskell path:
fibonaccis = 0 : 1 : zipWith (+) fibonaccis (tail fibonaccis)
This is what I tried to accomplish using my original function. For me, the solution with the naming of cards reads as "add the two previous elements to create a new one", and the solution "lazy cat" reads as "attach the stream with its first delay." How can I โjoin a stream with its first delayโ without having a sequence in the top-level namespace?
source share