Reputation: 1665
If these two expressions are equivalent
CL-USER> (lambda (x) (+ x 10))
#<FUNCTION (LAMBDA (X)) {530321CB}>
CL-USER> #'(lambda (x) (+ x 10))
#<FUNCTION (LAMBDA (X)) {5303226B}>
then why do I get the illegal function call error here
CL-USER> (#'(lambda (x) (+ x 10)) 10)
while this
CL-USER> ((lambda (x) (+ x 10)) 10)
20 (5 bits, #x14, #o24, #b10100)
works perfectly well?
PS I am using SBCL.
Upvotes: 2
Views: 142
Reputation: 139391
Different valid LAMBDAs
(lambda (x) (+ x 10))
LAMBDA
is a macro which expands to (function (lambda ...))
.
#'(lambda (x) (+ x 10))
#'
is a reader macro which expands at read time into (function ...)
.
((lambda ...) ...)
is built-in syntax in Common Lisp. It's defined as a valid form, a valid Lisp expression.
Invalid Lisp form syntax using a LAMBDA
((function (lambda ...)) ...)
is not valid syntax in Lisp.
Valid syntax of compound Lisp forms
There are only the following compound forms valid in Common Lisp:
(<special-operator> ...)
for one of the built-in special operators(<macro-operator> ...)
(<function-operator> ...)
(<lambda-expression> ...)
The operators are symbols. The latter then has a lambda expression as its first element. Example:
((lambda (x) (1+ x)) 41)
Other syntactic variants are not valid in Common Lisp. Thus ((function (lambda ...)) ...)
and also (#'(lambda ...) ...)
is not valid syntax.
Note
above is slightly confusing, but that's how it is defined in the language standard. The lambda
macro was added later after the initial design of Common Lisp. It allows us to write similar to Scheme:
(mapcar (lambda (x) (+ x 2)) '(1 2 3))
But it is still not the case that the first element of a list gets evaluated, like in Scheme.
Upvotes: 8
Reputation: 27434
The reason is just a syntactic rule: a form to be interpreted as a function call can be either (see the Common Lisp Glossary):
a) function form, a form that is a list and that has a first element which is the name of a function to be called on arguments which are the result of evaluating subsequent elements of the function form.
b) a lambda form, a form that is a list and that has a first element which is a lambda expression representing a function to be called on arguments which are the result of evaluating subsequent elements of the lambda form.
In other words, a list which is form which must be interpreted as a function call can have as first element only either a symbol, the function name, or a list starting with lambda
, i.e. a lambda expression. No other expressions are allowed (and #'x
is just an abbreviation for (function x)
, which is not one of the two cases).
This is due to the well known fact that Common Lisp follows the Lisp-2 model (see What is the difference between Lisp-1 and Lisp-2?).
Upvotes: 7