在Common Lisp中应用:是一次调用的函数,还是列表中每个元素的一次?

Dev*_*ius 1 lisp common-lisp

我试图完全理解申请的方式,但找不到足够明确的解释......鉴于此:

http://clhs.lisp.se/Body/26_glo_a.htm#apply

还有这个:

http://clhs.lisp.se/Body/f_apply.htm

假设我执行以下操作:

(defun sum (L)
  (apply #'+ L))
Run Code Online (Sandbox Code Playgroud)

然后调用以下内容:

(sum '(1 2 3 4 5))
Run Code Online (Sandbox Code Playgroud)

它做了以下事情:

(+ 1 2 3 4 5)
Run Code Online (Sandbox Code Playgroud)

或以下:

(+ 1 (+ 2 (+ 3 (+ 4 5))))
Run Code Online (Sandbox Code Playgroud)

换句话说,如果我写下面这个函数:

(defun sum2 (L)
  (if (null L)
      0
      (+ (first L) (sum2 (rest L)))))
Run Code Online (Sandbox Code Playgroud)

是否与我上面的函数完全相同?

Rai*_*wig 6

(apply #'+ '(1 2 3 4 5))
Run Code Online (Sandbox Code Playgroud)

基本上是一样的

(+ 1 2 3 4 5)
Run Code Online (Sandbox Code Playgroud)

请注意,Common Lisp参数列表通常具有有限的长度.最大参数列表长度取决于实现,可以低至50.请参见变量call-arguments-limit.

如果要添加更大的数字列表,请使用reduce:

(reduce #'+ '(1 2 3 4 5))
Run Code Online (Sandbox Code Playgroud)