Reputation: 190709
Lisp's APPLY is for calling functions with computed argument stored in lists.(Modified from Rainer's comment)
For example, the following code changes (list 1 2 3) to (+ 1 2 3).
(apply #'+ '(1 2 3))
However, Python's apply does what Lisp's funcall does, except for some minor differences (input is given as tuple/list)
(defun add (x y) (+ x y)) (funcall #'add 1 2) or (funcall #'(lambda (x y) (+ x y)) 10 2)
apply(lambda x,y : x+y, [1,2])
What do you think? Are there more differences between Lisp's funcall and Python's apply?
Upvotes: 2
Views: 5104
Reputation: 5766
Both Lisp's and Python's apply function do the same thing -- given a function f and a list of parameters p, apply f to p. The only difference is that Python's apply also accepts a dictionary for keyword arguments. In Lisp, these would be included in the parameter list as :keyword
arguments.
Upvotes: 1
Reputation: 21258
In Common Lisp (funcall #'fun 1 (list 2 3 4))
is exactly the same as (fun 1 (list 2 3 4))
, whereas (apply #'fun 1 (list 2 3 4))
would mean different things depending on the arity of fun.
* (defun bleargh (a &rest b) (cons a b))
BLEARGH
* (funcall #'bleargh 1 (list 1 2 3))
(1 (1 2 3))
* (apply #'bleargh 1 (list 1 2 3))
(1 1 2 3)
So FUNCALL and APPLY do very different things, as it were.
Upvotes: 4
Reputation: 229583
I don't see why you claim Lisp's apply()
would do anything different than Python's. Both functions take a function and a list and then call the function with the list elements as arguments. ((+ 1 2 3)
is an call to +
with arguments 1
, 2
and 3
, isn't it?) To me it looks like both apply
s do exactly the same thing.
funcall
on the other hand tales a function and several separate arguments (not a list containing arguments) and applies the function to these arguments.
Upvotes: 2
Reputation: 12961
Is there any reason why Python chose the name apply not funcall?
Because it's Python, not LISP. No need to have the same name, funcall
is a LISP command and apply
is something different in Python.
apply
is deprecated in Python, use the extended call syntax.
Old syntax:
apply(foo, args, kwargs)
New syntax:
foo(*args, **kwargs)
Upvotes: 8
Reputation: 319551
Deprecated since version 2.3: Use the extended call syntax with
*args
and**keywords
instead.
removed in py3k.
Upvotes: 2