&rest in common lisp

tsu*_*ere 0 lisp macros function common-lisp

&rest对普通 lisp 的作用感到困惑。这可能是一个代表我的意思的例子:

(defmacro switch (value &rest pairs)
             .... 
)
Run Code Online (Sandbox Code Playgroud)

&rest 和pairs 到底是什么意思?

Ren*_*nzo 6

函数(或宏)定义中的最后一个参数可以以&rest. 在这种情况下,当函数(或宏)被调用时,所有未绑定到前一个参数的参数都被收集到一个绑定到最后一个参数的列表中。这是一种向函数或宏提供未指定数量参数的方法。

例如:

CL-USER> (defun f (a &rest b)
           (list a (mapcar #'1+ b)))
F
CL-USER> (f 1 2 3 4 5)
(1 (3 4 5 6))
CL-USER> (f 1)
(1 NIL)
CL-USER> (f 1 2 3)
(1 (3 4))
CL-USER> (defmacro m (f g &rest pairs)
           (let ((operations (mapcar (lambda (pair) (list g (first pair) (second pair))) pairs)))
             `(,f (list ,@operations))))
M
CL-USER> (macroexpand-1 '(m print + (1 2) (3 4) (5 6)))
(PRINT (LIST (+ 1 2) (+ 3 4) (+ 5 6)))
T
CL-USER> (m print + (1 2) (3 4) (5 6))
(3 7 11)
Run Code Online (Sandbox Code Playgroud)

请注意,如果没有剩余参数,则传递给最后一个参数的列表为空。