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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With