I would like to create a function that returns a lazily extended infinite sequence of Fibonacci numbers.
Right now, I can make my sequence available in the top-level namespace like this:
(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 lose control over the garbage collection.
I am looking to do something like:
(defn fibonacci-numbers-fn []
(lazy-cat [0 1] (map + (fibonacci-numbers-fn) (rest (fibonacci-numbers-fn)))))
This clearly will not work because I will end up creating O(2^n) sequences. I think I am asking how to create a self-referential lazy sequence in a function-local 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 [[a b]] [b (+ a b)]) [0 1]))), I'm interested in a version similar to the canonical Haskell way:
fibonaccis = 0 : 1 : zipWith (+) fibonaccis (tail fibonaccis)
This is what I was trying to accomplish with my original function. To me, the map-iterate solution reads like "add the previous two elements to create a new one" and the lazy-cat solution reads like "join a stream with its first lag". How can I "join a stream with its first lag" without having the sequence in the top-level namespace?
defnneeds[]but SO won't let me make a 2-character edit.(╯°□°)╯︵ ┻━┻- noahlz