common-lispclos

defgeneric with optional and keyword arguments


I want to define a generic function in CL that takes an optional and a keyword argument both of which have a default value. I tried

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

but this throws Invalid &OPTIONAL argument specifier #1=(SZ 1)

So what is the proper way to do this sort of thing?


Solution

  • afaik you can't provide defaults in defgeneric. You would have to do this in the concrete implementation (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