Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lisp's apply and funcall vs Python's apply

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?

like image 604
prosseek Avatar asked Dec 10 '25 22:12

prosseek


2 Answers

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)
like image 163
leoluk Avatar answered Dec 12 '25 11:12

leoluk


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.

like image 22
Vatine Avatar answered Dec 12 '25 10:12

Vatine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!