休息引數

在所需引數之後,可以使用關鍵字 &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