I would like to know why most Common Lisp code I see has things like
(mapcar #'(lambda (x) (* x x)) '(1 2 3))
instead of just
(mapcar (lambda (x) (* x x)) '(1 2 3)),
which seems to work as well. I am beginning to learn Common Lisp, and having some background in Scheme, this intrigues me.
Edit: I know that you need #’ with function names because they live in a different namespace than variables. My question is just about #’ before lambda, as lambda already returns a function object (I think). The fact that #’-less lambdas work because of a macro expansion just makes it more intriguing…
#'foois an abbreviation for(function foo)by the reader.In CL, there are several different namespaces,
#'fooor(function foo)will return the functional value offoo.You may want to search for “Lisp-1 vs. Lisp-2”, check other Stackoverflow questions, or read an old article by Pitman and Gabriel in order to learn more about the concept of multiple namespaces (also called slots or cells of symbols).
The reason that, in the case of lambda, the
#'may be omitted in CL is that it is a macro, which expands thusly (taken from the Hyperspec):#'may still be used for historic reasons (I think that in Maclisplambdas didn’t expand to the function form), or because some people think, that tagging lambdas with sharpquotes may make the code more readable or coherent. There may be some special cases in which this makes a difference, but in general, it doesn’t really matter which form you choose.I guess you can think of it like this:
(function (lambda ...))returns the function(lambda ...)creates. Note thatlambdain the CL Hyperspec has both a macro AND a symbol entry. From the latter:From the documentation of
function:I think the difference is also related to calling lambda forms like this:
((lambda ...) ...)where it is treated as a form to be evaluated, vs.(funcall #'(lambda ...) ...). If you want to read more on the topic, there is a c.l.l thread about it.Some quotes from that thread:
and: