How to require keyword arguments in Common Lisp? -
given
(defun show-arg (a) (format t "a ~a~%" a)) (defun show-key (&key a) (format t "a ~a~%" a))
evaluating
(show-arg)
will lead error saying "invalid number of arguments: 0", where
(show-key)
will display a nil
how can show-key
signal error show-arg
does? there way other using (unless (error "a required"))
in function body? fond of keyword arguments , use them constantly, , want them required.
keyword arguments optional, need manually check if they're given , signal error if needed. better not require keyword arguments though. compiler won't recognize them required , won't given error message missing arguments @ compile time.
if want require them, can specify arguments 3 element list; first element being argument, second default value , third variable true if argument given. checking third element better checking keyword itself, because can tell difference between nil
default, , nil
user gave argument.
(defun foo (&key (keyarg nil keyargp)) (unless keyargp (error "keyarg required.")) (* keyarg 2))
edit
now think bit more, there way compile time errors missing keyword arguments. define compiler macro function:
(defun foo (&key b c d) (* b c d)) (define-compiler-macro foo (&whole whole &key (a nil ap) (b nil bp) (c nil cp) (d nil dp)) (declare (ignore b c d)) (unless (and ap bp cp dp) (error "missing arguments...")) whole)
Comments
Post a Comment