The Common Lisp HyperSpec says in the funcall
entry that
(funcall function arg1 arg2 ...) == (apply function arg1 arg2 ... nil) == (apply function (list arg1 arg2 ...))
Since they are somehow equivalent, when would you use apply
, and when funcall
?
to indicate the value of a symbol in the value namespace and use it as a function, Lisp requires to use funcall , as in (funcall fn &rest arguments) , for the symbol fn . to indicate the functional value of a symbol or of an expression, Lisp uses the special form (function fn) , which is commonly abbreviated as #' .
funcall applies function to args. If function is a symbol, it is coerced to a function as if by finding its functional value in the global environment.
To run the function, use M-: ( eval-expression ) and type (count-words-buffer) then RET . If the function needed arguments, you'd need to add them after the function name, e.g. (my-function "first argument" 'second-argument) . Alternatively, go to the *scratch* buffer and type your code (e.g. (count-word-buffers) ).
You should use funcall
if you have one or more separate arguments and apply
if you have your arguments in a list
(defun passargs (&rest args) (apply #'myfun args))
or
(defun passargs (a b) (funcall #'myfun a b))
apply
is useful when the argument list is known only at runtime, especially when the arguments are read dynamically as a list. You can still use funcall
here but you have to unpack the individual arguments from the list, which is inconvenient. You can also use apply
like funcall
by passing in the individual arguments. The only thing it requires is that the last argument must be a list:
> (funcall #'+ 1 2) 3 > (apply #'+ 1 2 ()) 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With