common-lisp Functions as first class values Defining anonymous functions


Example

Functions in Common Lisp are first class values. An anonymous function can be created by using lambda. For example, here is a function of 3 arguments which we then call using funcall

CL-USER> (lambda (a b c) (+ a (* b c)))
#<FUNCTION (LAMBDA (A B C)) {10034F484B}>
CL-USER> (defvar *foo* (lambda (a b c) (+ a (* b c))))
*FOO*
CL-USER> (funcall *foo* 1 2 3)
7

Anonymous functions can also be used directly. Common Lisp provides a syntax for it.

((lambda (a b c) (+ a (* b c)))    ; the lambda expression as the first
                                   ; element in a form
  1 2 3)                           ; followed by the arguments

Anonymous functions can also be stored as global functions:

(let ((a-function (lambda (a b c) (+ a (* b c)))))      ; our anonymous function
  (setf (symbol-function 'some-function) a-function))   ; storing it

(some-function 1 2 3)                                   ; calling it with the name

Quoted lambda expressions are not functions

Note that quoted lambda expressions are not functions in Common Lisp. This does not work:

(funcall '(lambda (x) x)
         42)

To convert a quoted lambda expression to a function use coerce, eval or funcall:

CL-USER > (coerce '(lambda (x) x) 'function)
#<anonymous interpreted function 4060000A7C>

CL-USER > (eval '(lambda (x) x))
#<anonymous interpreted function 4060000B9C>

CL-USER > (compile nil '(lambda (x) x))
#<Function 17 4060000CCC>