可选参数

可以使用 &OPTIONAL 关键字在必需参数之后指定可选参数。它后面可能有多个可选参数。

(defun foobar (x y &optional z)
  (format t "X (~s) and Y (~s) are required.~@
             Z (~s) is optional.~%"
          x y z))

(foobar 10 20)
; X (10) and Y (20) are required.
; Z (NIL) is optional.
;=> NIL
(foobar 10 20 30)
; X (10) and Y (20) are required.
; Z (30) is optional.
;=> NIL

默认值

通过使用列表指定参数,可以为可选参数指定默认值; 第二个值是默认值。只有在给出参数时才会评估默认值表单,因此它可以用于副作用,例如发出错误信号。

(defun foobar (x y &optional (z "Default"))
  (format t "X (~s) and Y (~s) are required.~@
             Z (~s) is optional.~%"
          x y z))

(foobar 10 20)
; X (10) and Y (20) are required.
; Z ("Default") is optional.
;=> NIL
(foobar 10 20 30)
; X (10) and Y (20) are required.
; Z (30) is optional.
;=> NIL

检查是否给出了可选参数

可以在默认值之后将第三个成员添加到列表中; 变量名称,如果给出了参数,则为 true;如果未给出,则为 NIL(并且使用默认值)。

(defun foobar (x y &optional (z "Default" zp))
  (format t "X (~s) and Y (~s) are required.~@
             Z (~s) is optional. It ~:[wasn't~;was~] given.~%"
          x y z zp))

(foobar 10 20)
; X (10) and Y (20) are required.
; Z ("Default") is optional. It wasn't given.
;=> NIL
(foobar 10 20 30)
; X (10) and Y (20) are required.
; Z (30) is optional. It was given.
;=> NIL