带有可选参数和关键字参数的 defgeneric

Sam*_*ins 2 common-lisp clos

我想在 CL 中定义一个通用函数,它接受一个可选参数和一个关键字参数,这两个参数都有一个默认值。我试过

(defgeneric read-one (buffer &optional (sz 1) &key (signed '()))
Run Code Online (Sandbox Code Playgroud)

但这会抛出 Invalid &OPTIONAL argument specifier #1=(SZ 1)

那么做这种事情的正确方法是什么?

lee*_*ski 5

afaik 你不能在 defgeneric 中提供默认值。您必须在具体实现中执行此操作(defmethod

(defgeneric read-one (buffer &optional sz &key signed))

(defmethod read-one (buffer &optional (sz 1) &key (signed '()))
  (format t "~a, ~a, ~a~%" buffer sz signed))

CL-USER> (read-one (list 1 2 3) )
;; (1 2 3), 1, NIL
;; NIL

;; CL-USER> (read-one (list 1 2 3) 101 :signed t)
;; (1 2 3), 101, T
;; NIL
Run Code Online (Sandbox Code Playgroud)

  • 通用函数 Lambda 列表 -> http://www.lispworks.com/documentation/HyperSpec/Body/03_db.htm (3认同)