Search code examples
clojurefactorial

What's wrong with this factorial function in clojure


I have this function:

(defn ! [x]
  (let [n x product 1]
    (if (zero? n)
        product
        (recur (- n 1) (* product n)))))

and I got error: java.lang.IllegalArgumentException: Mismatched argument count to recur, expected: 1 args, got: 2 (NO_SOURCE_FILE:33)

but this factorial from other SO question work fine. Why?

(defn fact [x]
    (loop [n x f 1]
        (if (= n 1)
            f
            (recur (dec n) (* f n)))))

Solution

  • You can't recur on let.

    When you recur here, you are actually recurring on the function definition which has one argument hence java.lang.IllegalArgumentException: Mismatched argument count to recur, expected: 1 args, got: 2 (NO_SOURCE_FILE:33).

    On the second example (s)he's using loop which you should use when you want to recur on some other arguments, other than the functions.