While working on the Clojure Koans, I had to calculate the factorial of a number iterativly, I did find the solution, but I have a question about the difference between 2 solutions, one that works and one that doens’t, although I don’t understand why:
The one that works:
(defn factorial [n]
(loop [n n
acc 1]
(if (zero? n)
acc
(recur (dec n) (* n acc )))
)
The one that desn’t:
(defn factorial [n]
(loop [n n
acc 1]
(if (zero? n)
1
(recur (dec n) (* n acc )))
)
Note that the only difference is the returned value of the If block if the condition is met.
The second
factorialfunction always returns1. The code is built to use an accumulator variable (acc), and the first code block gets it right by returning this accumulator variable.A
factorialfunction can be written to return1, though, if an accumulator variable is not used. Since this method does not utilizeloop/recur, it can cause a stack overflow easily: try(fact 5000).(source)