When do you use “apply” and when “funcall”?

前端 未结 3 1158
遥遥无期
遥遥无期 2021-02-04 02:33

The Common Lisp HyperSpec says in the funcall entry that

(funcall function arg1 arg2 ...) 
==  (apply function arg1 arg2 ... nil) 
==  (app         


        
3条回答
  •  无人及你
    2021-02-04 03:10

    Well I think a good rule of thumb would be: use apply when you can't use funcall: the latter is clearer but is also less general than apply in that it doesn't allow you to call a function whose number of arguments is only known at runtime.

    Of course it is only good practice and you could systematically do this the ugly way (systematically using apply), but as you've probably noticed, using the ugly way when a very similar but cleaner way is available is not very common-lisp-y.

    Example of function that needs apply instead of funcall: could you implement map in such a way that (map #'+ '(1 2) '(2 3)) and (map #'+ '(1 2) '(2 3) '(3 4)) both work (which is the case with the standard function) without using apply (or eval, which is cheating)?

    EDIT: as has also been pointed out, it would be silly to write:(funcall func (first list) (second list) (third list) etc.) instead of (apply func list).

提交回复
热议问题