Common Lisp the Language 2nd Edition


next up previous contents index
Next: Simple Sequencing Up: Control Structure Previous: Generalized Variables

7.3. Function Invocation

The most primitive form for function invocation in Lisp of course has no name; any list that has no other interpretation as a macro call or special form is taken to be a function call. Other constructs are provided for less common but nevertheless frequently useful situations.


[Function]
apply function arg &rest more-args

This applies function to a list of arguments.

old_change_begin
The function may be a compiled-code object or a lambda-expression or a symbol; in the latter case the global functional value of that symbol is used (but it is illegal for the symbol to be the name of a macro or special form).
old_change_end

change_begin
X3J13 voted in June 1988 (FUNCTION-TYPE)   to allow the function to be only of type symbol or function; a lambda-expression is no longer acceptable as a functional argument. One must use the function special form or the abbreviation #' before a lambda-expression that appears as an explicit argument form.
change_end

The arguments for the function consist of the last argument to apply appended to the end of a list of all the other arguments to apply but the function itself; it is as if all the arguments to apply except the function were given to list* to create the argument list. For example:

(setq f '+) (apply f '(1 2)) => 3
(setq f #'-) (apply f '(1 2)) => -1
(apply #'max 3 5 '(2 7 3)) => 7
(apply 'cons '((+ 2 3) 4)) =>
((+ 2 3) . 4) not (5 . 4)
(apply #'+ '()) => 0

Note that if the function takes keyword arguments the keywords as well as the corresponding values must appear in the argument list:

(apply #'(lambda (&key a b) (list a b)) '(:b 3)) => (nil 3)

This can be very useful in conjunction with the &allow-other-keys feature:

(defun foo (size &rest keys &key double &allow-other-keys)
(let ((v (apply #'make-array size :allow-other-keys t keys)))
(if double (concatenate (type-of v) v v) v)))
(if double (concatenate (type-of v) v v) v))) -keys t keys))) ble &allow-other-keys) plies function to a list of