[cl-faq] faq answer: What's the difference between APPLY and FUNCALL?
Larry Clapp
larry at theclapp.org
Thu Jun 22 20:34:52 CDT 2006
*** 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:
(funcall f arg1 arg2 arg3) == (apply f (list arg1 arg2 arg3))
(apply f arg1 arg2 list-of-args) == (funcall f ???)
-- L
More information about the cl-faq
mailing list