cirval
cirval

Reputation: 69

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

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))
)

Upvotes: 0

Views: 1139

Answers (2)

Matthias Wimmer
Matthias Wimmer

Reputation: 3999

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)

Upvotes: -1

MarkNFI
MarkNFI

Reputation: 556

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) ;; <== 
    )
)

Upvotes: 4

Related Questions