views:

102

answers:

3

I define a function in LISP, and it defines correctly. But whenever I try to call it, I get an error saying "The variable FACTORIAL is unbound."

I have tried this on both OS X and Windows 7, on LispWorks and Allegro. The function is -

(defun factorial (x)
   (if (= 1 x) 1
       (* x factorial (- 1 x))))

Any help is appreciated.

+3  A: 

It looks like you're missing a set of parentheses:

(defun factorial (x) 
   (if (= 1 x) 1 
       (* x (factorial (- 1 x))))) 

Without the () around factorial, Lisp thinks you're referring to a variable instead of a function.

Greg Hewgill
Almost–I almost missed the `(- 1 x)`, too. Though I don't know CL, so I could be totally off!
Isaac Hodes
@Isaac Hodes: I saw that too but I thought I'd leave it as an exercise for the OP. :)
Greg Hewgill
Good call–I was half-unsure if I were wrong about it, hence the comment haha. And it makes sense to leave it like that, too!
Isaac Hodes
+11  A: 

In the third line of your code, you're multiplying x times factorial times 1-x.

The first thing to notice is factorial isn't a variable: it's a function. As Common-Lisp is a Lisp-2, factorial isn't bound as a variable at all–it's bound as a function.

You need to be calling the factorial function on one less than x, not x less than one.

So:

(defun factorial (x)
   (if (= 1 x) 1
       (* x (factorial (- x 1)))))

…should do it.

Isaac Hodes
+1  A: 

To complete the answer of @Isaac Hodes, this show you that there is clearly 2 namspace for function and variable in CL. You wouldn't have the same error if you were in scheme. You can read more here.

mathk
It would still be wrong, since you still need the parentheses around the recursive call, but it would be wrong in a more interesting way.
John R. Strohm
Yes that is way I said "You wouldn't have the same error"
mathk