0

I trying to write simple factorial function in clojure, but i am getting this error:

java.lang.Long cannot be cast to clojure.lang.IFn

I know this error is usually due to an extra parenthesis, but I am not sure about this case.

First I wrote function in LISP, and it works as it should. Code:

(defun factorial (n)
    (if (= n 1) 
        1
        (* (factorial (1- n)) n )
    )
)
(factorial 5)

Then I tried it in clojure, where it doesn't work. Clojure code:

(defn factorial [n]
    (if (= n 1) 
        1
        (* (factorial(n)) n)
    )
)

(defn -main
    [& args]
    (println(factorial 5))
)
amalloy
  • 89,153
  • 8
  • 140
  • 205
cirval
  • 69
  • 11
  • Reopened this question: the duplicate question was about a completely different problem in a different incorrectly-implemented fibonacci function. – amalloy Mar 15 '17 at 01:11

2 Answers2

4

You've got an extra set of parens in your recursive call to factorial, probably because you meant to decrement n, it should be

(defn factorial [n]
    (if (= n 1) 
        1
        (* (factorial (dec n)) n) ;; <== 
    )
)
MarkNFI
  • 556
  • 2
  • 9
-1

As MarkNFI showed decrementing has its own operator inc.

But to show you the problem in your code:

(defun factorial (n)
    (if (= n 1) 
        1
        (* (factorial (1- n)) n ) ;; (1- n) must be changed to (dec n) or (- n 1)
    )
)
(factorial 5)

(1- n) is not the way operators in clojure work. You have to place the operator first. So in your case it would be: (- n 1)

Matthias Wimmer
  • 3,789
  • 2
  • 22
  • 41