为什么Common Lisp的apply函数给出了不同的结果?

Rom*_*rio 1 common-lisp

当我在Emacs上尝试此代码时SLIME,该apply函数会给出不同的结果.是不是应该给出相同的结果?为什么它会给出不同的结果?谢谢.

CL-USER> (apply #'(lambda (n)
             (cons n '(b a))) '(c)) 

(C B A)

CL-USER> (cons '(c) '(b a)) 

((C) B A)
Run Code Online (Sandbox Code Playgroud)

Jay*_*Jay 6

cons元素列表作为参数.所以(cons 'x '(a b c d))会回来(x a b c d).

apply接受一个函数和一个参数列表 - 但参数不会作为列表传递给函数!它们将被拆分并单独传递:

(apply #'+ '(1 2 3))

6
Run Code Online (Sandbox Code Playgroud)

(实际上,它需要一个函数,几个参数,其中最后一个必须是一个列表 - 这个列表将被拆分并被视为"函数的其余参数".例如,尝试,(apply #'+ 5 1 '(1 2 3))将返回12)

现在到你的代码:

传递给apply函数的最后一个参数是'(c)一个包含一个元素的列表c.Apply会将其视为参数列表,因此传递lambda-form 的第一个参数c.

在第二个调用中,您'(c)作为第一个参数传递给cons.这是一个列表,它正确地包含在结果列表的第一位:( (c) b a).

如果你做的话,第二次调用将等同于第一次调用

(cons 'c '(b a))

(c b a)
Run Code Online (Sandbox Code Playgroud)

如果你做的话,第一个电话会相当于第二个电话

(apply #'(lambda (n) (cons n '(b a))) '((c)))

((c) b a)
Run Code Online (Sandbox Code Playgroud)