1

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?

3
  • Every time you recur back into the loop, current, next, and result take on new values. More importantly, x will always have its same original value --- if you call the function with x set to 1, it will always be 1 and never 0. Hence the loop will never exit. Commented May 15, 2018 at 9:19
  • OK, but shouldn't (dec result) change x to 0? Commented May 15, 2018 at 9:21
  • 2
    No, it'll decrement result. So check that binding Commented May 15, 2018 at 9:21

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed! Now I get it, I was trying to compare wrong part of binding. Thanks for that clue!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.