common-lisp 休息参数

示例

可以&REST在所需参数之后的关键字中给定一个单个剩余参数。如果存在这样的参数,则该函数可以使用多个参数,这些参数将被分组到其余参数的列表中。请注意,该变量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

休息和关键字参数一起

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

(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

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

(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