[3-10] What is the difference between FUNCALL and APPLY?

FUNCALL is useful when the programmer knows the length of the argument
list, but the function to call is either computed or provided as a
parameter.  For instance, a simple implementation of MEMBER-IF (with
none of the fancy options) could be written as:

(defun member-if (predicate list)
  (do ((tail list (cdr tail)))
      ((null tail))
   (when (funcall predicate (car tail))
     (return-from member-if tail))))

The programmer is invoking a caller-supplied function with a known
argument list.

APPLY is needed when the argument list itself is supplied or computed.
Its last argument must be a list, and the elements of this list become
individual arguments to the function.  This frequently occurs when a
function takes keyword options that will be passed on to some other
function, perhaps with application-specific defaults inserted.  For

(defun open-for-output (pathname &rest open-options)
  (apply #'open pathname :direction :output open-options))

FUNCALL could actually have been defined using APPLY:

(defun funcall (function &rest arguments)
  (apply function arguments))
Go Back Up

Go To Previous

Go To Next