Search code examples
lispcommon-lispclisp

CLISP: variable <x> has no value when returning from function


I'm running into the following problem in Common Lisp (using CLISP)... The following code runs just fine and as expected ('->' designates what the function call returns):

(list (quote x)) -> (X)

However, when I try to move this behavior into a function,

(defun quote-it (x) 
    (list (quote x)))

And I call the function, I get an unexpected error.

(quote-it x) -> SYSTEM::READ-EVAL-PRINT: variable X has no value

Can anyone explain what's going on here?

Thanks.


Solution

  • If you compile quote-it, you will get a warning that you are not using the value of the argument x. This should serve as a, well, warning that something is amiss.

    Specifically, Common Lisp evaluates the expression (quote-it x) by, first, evaluating x, and, second, passing the result to quote-it. Since you never gave x a value, the first step fails.

    Try these:

    (defparameter x 42)
    (quote-it x)
    ==> (x)
    (quote-it 'y)
    ==> (x)
    

    As you can see, it does not matter what you pass to quote-it.

    PS: generally speaking, the special operator quote is rarely used in functions. It is a common tool in macros though, as suggested by a commenter:

    (defmacro quote-it (x) `(list ',x))
    

    If you tell us what you want to achieve (in a separate question), we (the SO community) might be of more help.