Elisp: Apply Function (List to Args)
Sometimes you have a list, you want to feed them as arguments to a function.
There are 2 ways to do that:
- Use the function
apply
, e.g.(apply 'f (list 2 3 4))
- Use the Backquote Reader Macro
apply
-
(apply FUNCTION &rest args_or_list)
Call FUNCTION with args_or_list.
If the last argument in args_or_list is a list, it is flattened out and feed as args to the function.
;; test function (defun ff (x y z) "return args as one string" (format "%s %s %s" x y z)) ;; normal usage (ff 2 3 4) ;; "2 3 4" ;; HHHH------------------------------ ;; use apply, to turn a list into args (apply 'ff (list 2 3 4)) ;; "2 3 4" ;; HHHH------------------------------ ;; multi arg example. the last arg, if list, is turned into args (apply 'ff 2 (list 3 4)) ;; "2 3 4"
funcall
-
(funcall FUNCTION &rest args)
Call FUNCTION with args.
💡 TIP: this is useful when the function name is a variable, value known only at run-time.
;; test function (defun ff (x y z) "return args as one string" (format "%s %s %s" x y z)) ;; normal usage (ff 2 3 4) ;; "2 3 4" ;; use funcall (funcall 'ff 2 3 4) ;; "2 3 4"