Lambda Expression

In the CommonLisp language, an expression that begins with the symbol LAMBDA, followed by a parameter list called a LambdaList?, and an optional body of declarations and expressions.

When such an expression is evaluated, it produces a function-object which can be called with the arguments implied by the LambdaList?, and whose body expressions have access to all the lexical variables that are visible at that point. The ones that are outside of the expression, whose bindings were established before it was created, are captured. This is why the resulting object is called a LexicalClosure.

A lambda expression can be used in a number of contexts; for example, it is evaluated specially when it's the first element of a form, where it serves in place of a function name to just specify the function directly, so that the second expression of these two:

  (defun add (x y) (+ x y))
  (add 1 2)

can be written with ADD replaced by a lambda expression that does the same thing as the ADD function:

  ((lambda (x y) (+ x y)) 1 2)

In a context that just calls for the evaluation of the expression, a lambda expression is handled by a macro called LAMBDA which basically translates (LAMBDA X) into (FUNCTION (LAMBDA X)) for any X. In this manner, the special operator FUNCTION is called with the source code of the lambda expression as its parameter, and creates the closure from it. CL programmers often do this manually in contexts where they want to compute the function object from the expression. They write #'(LAMBDA (...) ...) rather than just (LAMBDA (...) ...), where #'X (SharpQuote) is the standard read-time abbreviation for (FUNCTION X).

Lisp's COMPILE function, which gives a programmer access to the compiler, can accept a lambda expression. It will produce a compiled function object. Example:

  (let ((compiled-adder (compile nil '(lambda (x y) (+ x y)))))
    (funcall compiled-adder 1 2))

Note that the lambda expression is quoted, so that it's not evaluated via the LAMBDA macro to produce a closure!

The result is not a closure because it doesn't capture anything in the lexical context. COMPILE is a function, and as such has no access to the lexical environment of the caller. But COMPILE can take a ready-made closure and compile that. Just drop the quote from the lambda expression so that it's evaluated, and the resulting closure is passed.

The COMPILE function lets you do cool stuff, like write a program that constructs the source code for a Lisp function, and then compiles it. Without exception, all commercial Lisp implementations have compilers that produce native machine code.

See LambdaCalculus, LambdaTheUltimate, AnonymousFunction

CategoryLanguageFeature CategoryCommonLisp

EditText of this page (last edited November 26, 2005) or FindPage with title or text search