cl-faq  

[cl-faq] faq answer: What's the difference between APPLY and FUNCALL?

Larry Clapp
Thu, 22 Jun 2006 18:35:19 -0700

*** 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


_______________________________________________
cl-faq mailing list
cl-faq@lispniks.com
http://www.lispniks.com/mailman/listinfo/cl-faq