Search code examples
loopsclojureinfinite

Clojure - Fibonacci using loop recur - comes to infinite loop


I'm trying to get a Fibonacci numbers using loop-recur construction:

(defn fibo-looprecur [x]
  (loop [current 0
         next 1
         result x]
       (if (= x 0) current (recur next (+' current next) (dec result))))
)

When I run it, it works OK with 0, but when I put 1 to fibo-looprecur, it goes to an infinite loop. What could cause that behaviour?


Solution

  • Clojure works with values not reference types; in other words x and result do not point to the same value but are separate bindings. When you decrement result it has no effect on x, and therefore you never hit your base case of x = 0.

    If you change your condition to check result instead of x you'll get the expected results.

    (defn fibo-looprecur [x]
      (loop [current 0
             next 1
             result x]
        (if (= result 0) current (recur next (+' current next) (dec result)))))
    
    (map fibo-looprecur (range 10))
    => (0 1 1 2 3 5 8 13 21 34)