Search code examples
recursionclojurefibonacci

lazily calling functions for infinite sequence clojure


I am very new to clojure and want to make obvious programs.

(def fib (conj fib (apply + (take-last 2 fib)))) Doesn't work because of no lazy evaluation, nor indication of the start being [0 1]

(def fib ( (fn [array] (recur (conj array (apply + (take-last 2 array))))) [0 1])) And here recur is seemingly not lazily evaluated.

Highly related to ( a recursive Fibonacci function in Clojure ) however they use loops and counts or multi-arity. I was wondering if this problem was possible without this.

(def fib (lazy-cat [0 1] (map + fib (rest fib)))) is a very nice solution but somehow hides the operation of fx = fx-1 + fx-2, rather a shift and add all elements. Elegant but not so obvious to the original fibonacci definition.

Is there a way to avoid using map.


Solution

  • obvious is going to be highly subjective, but perhaps this can give you some ideas:

    user> (def fib ((fn f [a b] (lazy-seq (cons a (f b (+ a b))))) 0 1))
    #'user/fib
    user> (take 10 fib)
    (0 1 1 2 3 5 8 13 21 34)