Emacs Lisp: Apply Function (List to Args)
Sometimes you have a list, you want to feed them as arguments to a function.
There 2 ways to do that:
- Use the function
apply
- Use the Backquote Reader Macro
apply
-
(apply FUNCTION &rest args_or_list)
Call FUNCTION with args_or_list.
The last argument in args_or_list, if it is a list, it'll be 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 (equal (ff 2 3 4) "2 3 4") ;; define a list (setq xx '(2 3 4)) ;; use apply, to turn a list into args (equal (apply 'ff xx) "2 3 4") ;; true ;; the list can be shorter (setq xx '(3 4)) ;; use apply, to turn a list into args (equal (apply 'ff 2 xx) "2 3 4") ;; true
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 (equal (ff 2 3 4) "2 3 4") ;; use funcall (equal (funcall 'ff 2 3 4) "2 3 4") ;; t