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 fa开发者_运维问答ctorial (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.
You need to bind all variables and function calls you intend to use with brackets unless you want them to be symbols. About unbound errors, Paul Graham has a good example in his book: Ansi Common Lisp
One of the most common complaints you'll hear from Lisp is that a symbol has no value or is unbound. Several distinct problems show themselves in this way. Local variables, like those established by let and defun, are valid only within the body of the expression where they are created. So if we try to refer to such a variable outside the let that creates it:
> (progn (let ((x 10))
(format t "Here x = ~A.~%" x))
(format t "But now it's gone...~%") x)
精彩评论