休息参数

在所需参数之后,可以使用关键字 &REST 给出单个 rest 参数。如果存在这样的参数,则该函数可以采用多个参数,这些参数将被分组到 rest-parameter 中的列表中。请注意,变量 CALL-ARGUMENTS-LIMIT 确定可以在函数调用中使用的最大参数数,因此参数的数量限制为最小 50 个或更多参数的实现特定值。

(defun foobar (x y &rest rest)
  (format t "X (~s) and Y (~s) are required.~@
             The function was also given following arguments: ~s~%"
          x y rest))

(foobar 10 20)
; X (10) and Y (20) are required.
; The function was also given following arguments: NIL
;=> NIL
(foobar 10 20 30 40 50 60 70 80)
; X (10) and Y (20) are required.
; The function was also given following arguments: (30 40 50 60 70 80)
;=> NIL

休息和关键字参数在一起

rest-parameter 可以在关键字参数之前。在这种情况下,它将包含用户给出的属性列表。关键字值仍将绑定到相应的关键字参数。

(defun foobar (x y &rest rest &key (z 10 zp))
  (format t "X (~s) and Y (~s) are required.~@
             Z (~s) is a keyword argument. It ~:[wasn't~;was~] given.~@
             The function was also given following arguments: ~s~%"
          x y z zp rest))

(foobar 10 20)
; X (10) and Y (20) are required.
; Z (10) is a keyword argument. It wasn't given.
; The function was also given following arguments: NIL
;=> NIL
(foobar 10 20 :z 30)
; X (10) and Y (20) are required.
; Z (30) is a keyword argument. It was given.
; The function was also given following arguments: (:Z 30)
;=> NIL

可以在 lambda 列表的末尾添加关键字 &ALLOW-OTHER-KEYS,以允许用户提供未定义为参数的关键字参数。他们将进入休息列表。

(defun foobar (x y &rest rest &key (z 10 zp) &allow-other-keys)
  (format t "X (~s) and Y (~s) are required.~@
             Z (~s) is a keyword argument. It ~:[wasn't~;was~] given.~@
             The function was also given following arguments: ~s~%"
          x y z zp rest))

(foobar 10 20 :z 30 :q 40)
; X (10) and Y (20) are required.
; Z (30) is a keyword argument. It was given.
; The function was also given following arguments: (:Z 30 :Q 40)
;=> NIL