Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you use "apply" and when "funcall"?

Tags:

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?

like image 391
Frank Shearar Avatar asked Oct 05 '10 09:10

Frank Shearar


People also ask

When would you use a Funcall Lisp?

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 #' .

What does Funcall do in Lisp?

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.

How do I run a function in Emacs?

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) ).


2 Answers

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)) 
like image 154
denis Avatar answered Sep 29 '22 02:09

denis


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 
like image 23
Vijay Mathew Avatar answered Sep 29 '22 04:09

Vijay Mathew