The less-familiar parts of Lisp for beginners — lambda

Now, the newcomer to Lisp, arriving from C++, has certainly encountered lambda before, as part of a construct to build functions that can be passed to functions.  Just about any introduction to Lisp will show lambda forms being passed to mapcar or sort.  There is, however, a short digression we can go into in order to clear up some confusion.

While reading over Lisp code, you’ve almost certainly seen lambda used in two visually distinct ways:

(let ((my-list (list 1 2 3 4 5)))
  (mapcar #'(lambda (x) (* x 3)) my-list))

(let ((my-list (list 1 2 3 4 5)))
  (mapcar (lambda (x) (* x 3)) my-list))

What is the difference between these two?  Why do you sometimes see one form, and sometimes another?

You’ll recall we talked about read-macros, and that the form #’<STUFF> is rewritten (function <STUFF>).  The standard Lisp implementation also defines a macro for lambda, which expands to #’, as follows:

CL-USER> (macroexpand '(lambda (x) (* x 3)))
#'(LAMBDA (X) (* X 3))

So, in fact, there is no difference at all between the two forms, they are interpreted the same way by the Lisp instance.  It comes down to a matter of preference.  Personally, I use the prefixed form of lambda, because I find that it sticks out a bit more that way, a lambda is built a bit like a function invocation, and the syntactic prefix helps to separate that in my mind when quickly skimming through code.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.