Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is my LISP function an unbound variable?

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.

like image 889
sterling Avatar asked Aug 31 '10 01:08

sterling


3 Answers

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.

like image 58
Isaac Avatar answered Sep 28 '22 17:09

Isaac


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.

like image 24
Greg Hewgill Avatar answered Sep 28 '22 18:09

Greg Hewgill


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.

like image 34
mathk Avatar answered Sep 28 '22 17:09

mathk