Search the FAQ Archives

3 - A - B - C - D - E - F - G - H - I - J - K - L - M
N - O - P - Q - R - S - T - U - V - W - X - Y - Z
faqs.org - Internet FAQ Archives

FAQ: Lisp Frequently Asked Questions 3/7 [Monthly posting]
Section - [3-10] What is the difference between FUNCALL and APPLY?

( Part1 - Part2 - Part3 - Part4 - Part5 - Part6 - Part7 - Single Page )
[ Usenet FAQs | Web FAQs | Documents | RFC Index | Property taxes ]


Top Document: FAQ: Lisp Frequently Asked Questions 3/7 [Monthly posting]
Previous Document: [3-9] Closures don't seem to work properly when referring to the iteration variable in DOLIST, DOTIMES, DO and LOOP.
Next Document: [3-11] Miscellaneous things to consider when debugging code.
See reader questions & answers on this topic! - Help others by sharing your knowledge

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
instance:

(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))

User Contributions:

Comment about this article, ask questions, or add new information about this topic: