[cl-faq] faq answer: What's the difference between APPLY and FUNCALL?
Larry Clapp
larry at theclapp.org
Fri Jun 23 06:24:59 CDT 2006
2nd draft:
*** What's the difference between APPLY and FUNCALL?
In the simplest case, you use APPLY when you already have a list of
arguments:
(let ((args (list 1 2 3)))
(apply f args))
is the same as
(f 1 2 3)
You use FUNCALL when you have several separate arguments:
(funcall f 1 2 3) == (f 1 2 3)
Another difference is that APPLY will "spread out" its last argument
(which might be its only argument, as in the example above), which
must be a list, whereas FUNCALL won't.
(apply f '(1 2 3)) == (f 1 2 3)
(funcall f '(1 2 3)) == (f '(1 2 3))
(apply f 1 2 '(3 4 5)) == (f 1 2 3 4 5)
(funcall f 1 2 '(3 4 5)) == (f 1 2 '(3 4 5))
APPLY requires at least two arguments: a function to call and a list
of arguments to pass it, whereas FUNCALL requires only one argument, a
function to call; anything else is optional (as far as FUNCALL is
concerned).
Legal: (funcall f)
(apply f (list arg))
Illegal: (apply f)
But
Legal:
(defun f () 'foo)
(apply #'f nil)
=> FOO
FUNCALL can be implemented using APPLY, but not the other way 'round:
(defun my-funcall (function &rest args)
(apply function args)) ; can do it
(defun my-apply (function &rest args)
(funcall function ???)) ; can't do it
-- L
More information about the cl-faq
mailing list