Go to the first, previous, next, last section, table of contents.


Anonymous Functions

When giving function names as arguments to functions it is useful to give an actual function definition (i.e. a lambda expression) instead of the name of a function.

In Lisp, unlike most other programming languages, functions have no inherent name. As seen in the last section named-functions are created by storing a function in a special slot of a symbol, if you want, a function can have many different names: simply store the function in many different symbols!

So, when you want to pass a function as an argument there is the option of just writing down its definition. This is especially useful with functions like mapcar and delete-if. For example, the following form removes all elements from the list which are even and greater than 20.

(setq list (delete-if #'(lambda (x)
                                (and (zerop (% x 2))
                                     (> x 20)))
                            list))

The lambda expression is very simple, it combines two predicates applied to its argument.

Note that the function definition is quoted by #', not the normal '. This is a special shortcut for the function special form (like ' is a shortcut to quote). In general, #'x is expanded by the Lisp reader to (function x).

Special Form: function arg
This special form is nearly identical to the quote form, it always returns its argument without evaluating it. The difference is that the Lisp compiler knows to compile the arg into a byte-code form (unless arg is a symbol in which case it is not compiled).

What this means is when you have to quote a function, use the #' syntax.


Go to the first, previous, next, last section, table of contents.