funcall
funcall Function
Syntax:
funcall function &rest args → {result}*
Arguments and Values:
function—a function designator .
args—arguments to the function.
results—the values returned by the function.
Description:
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.
Examples:
(funcall #’+ 1 2 3) → 6
(funcall ’car ’(1 2 3)) → 1
(funcall ’position 1 ’(1 2 3 2 1) :start 1) → 4
(defun foo (x y) (cons x y)) → FOO
(foo 1 2) → (1 . 2)
(flet ((foo (x y) ‘(kons ,x ,y)))
(let ((foo (symbol-function ’+)))
(funcall #’foo
(funcall ’foo 1 2)
(funcall foo 1 2))))
→ (KONS (1 . 2) 3)
Exceptional Situations:
An error of type undefined-function should be signaled if function is a symbol that does not have a global definition as a function or that has a global definition as a macro or a special operator .
See Also:
apply, function, Section 3.1 (Evaluation)
Notes:
(funcall function arg1 arg2 ...)
≡ (apply function arg1 arg2 ... nil)
≡ (apply function (list arg1 arg2 ...))
The difference between funcall and an ordinary function call is that in the former case the function is obtained by ordinary evaluation of a form, and in the latter case it is obtained by the special interpretation of the function position that normally occurs.
We fixed the examples so that it is conforming, by not shadowing cons in the flet form.
Expanded Reference: funcall
Calling a function object
funcall calls a function with individually specified arguments, unlike apply which takes a trailing list.
(funcall #'+ 1 2 3)
=> 6
Calling a function stored in a variable
funcall is essential when the function to call is determined at runtime.
(let ((op #'*))
(funcall op 3 4))
=> 12
Using a symbol as a function designator
When given a symbol, funcall looks up its global function definition.
(funcall 'list 'a 'b 'c)
=> (A B C)
Higher-order programming with funcall
funcall is the standard way to invoke function arguments within higher-order functions.
(defun apply-twice (f x)
(funcall f (funcall f x)))
=> APPLY-TWICE
(apply-twice #'1+ 5)
=> 7
(apply-twice #'reverse '(1 2 3))
=> (1 2 3)
Difference between funcall with #' and a symbol
Using #'name captures the lexical function binding, while using a symbol always looks up the global definition.
(defun foo () :global)
=> FOO
(flet ((foo () :local))
(list (funcall #'foo)
(funcall 'foo)))
=> (:LOCAL :GLOBAL)