Earlier I promised to give some functions which take functions as arguments. Here they are:
> (funcall #'+ 3 4)
7
> (apply #'+ 3 4 '(3 4))
14
> (mapcar #'not '(t nil t nil t nil))
(NIL T NIL T NIL T)
Funcall
calls its first argument on its remaining arguments.
Apply
is just like funcall
, except that its final argument
should be a
list; the elements of that list are treated as if they were additional
arguments to a funcall
.
The first argument to mapcar
must be a function of one argument;
mapcar
applies this function to each element of a list and collects the
results in another list.
Funcall
and apply
are chiefly useful when their first argument is a
variable. For instance, a search engine could take a heuristic function
as a parameter and use funcall
or apply
to call that function on a
state description. The sorting functions described later use funcall
to call their comparison functions.
Mapcar
, along with nameless functions (see below), can replace many
loops.