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))
)
1
  • Reopened this question: the duplicate question was about a completely different problem in a different incorrectly-implemented fibonacci function. Commented Mar 15, 2017 at 1:11

2 Answers 2

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

Comments

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

1 Comment

It's Common Lisp snippet, 1- in CL is what dec in Clojure is.

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.