147pm
147pm

Reputation: 2239

common lisp: apply needs special treatment?

If I try this

(apply (first '(numberp)) '(17))

all is well, returning T. But this

(apply numberp '(17))

gets The variable NUMBERP is unbound.

But this

(apply #'numberp '(17))

works. I'm obviously missing something very basic here. . . .

Upvotes: 0

Views: 82

Answers (2)

PuercoPop
PuercoPop

Reputation: 6807

What (apply numberp '(17)) does is lookup the value of the variable numberp. This has nothing to do with apply. Unquoted symbols in the function position, the first element in the list, are looked-up in the function namespace, the successive elements are looked-up in the variable namespace.

If you try (+ x 1) you would get the same error. Or (symbol-function symbol-function) for that matter.

For (apply numberp '(17)) to work you would need to bind the variable numberp to a function. For example:

(let ((numberp 'numberp))
  (apply numberp '(17)))

Upvotes: 1

sds
sds

Reputation: 60014

What you are missing here is how the Common Lisp reading and evaluation works.

When you give CL text, e.g.,

(apply (first '(numberp)) '(17))

the reader (you can invoke it yourself!) parses it into the following list:

(apply (first (quote (numberp))) (quote (17)))

(note that ' is just syntactic sugar for quote) which is then evaluated like this:

  1. take the function binding of the first element of the list, apply
  2. evaluate the second list element:
    1. take the function binding of first
    2. evaluate the second list element:
      • since it is quoted, take it as is, get list of length 1 with element numberp
    3. apply first to that list, get numberp
  3. evaluate the 3rd list element:
    • since it is quoted, it is just the thing under quote, i.e., list of length 1 with element 17
  4. apply the first function (apply) to the arguments, i.e., apply the (function binding of) numberp to the list of one element - 17.

Your 2nd form differs from the 1st in that you have symbol numberp which is evaluated as a variable and thus you get your error.

In your 3rd form you use #'numberp which the reader transforms to (function numberp) which returns a function value which can be applied to the list.

In short, this is the result of Common Lisp being Lisp-2.

You might also find When to use 'quote in Lisp instructive.

Upvotes: 4

Related Questions