在 common lisp 中使用 &allow-other-keys
Usage of &allow-other-keys in common lisp
我想创建最通用的函数并决定使用键作为参数。
我想使用 allow-other-keys
因为我想使用任何键的功能。
让我告诉你:
(defun myfunc (a &rest rest &key b &allow-other-keys)
;; Print A
(format t "A = ~a~%" a)
;; Print B if defined
(when b
(format t "B = ~a~%" b))
;; Here ... I want to print C or D or any other keys
;; ??
)
(myfunc "Value of A")
(myfunc "Value of A" :b "Value of B")
(myfunc "Value of A" :b "Value of B" :c "Value of C" :d "Value of D")
我知道 rest
是剩余的参数,但它有一个数组。它不绑定值 c
或 d
甚至像关联列表一样构建它们(即像 (cdr (assoc 'c rest))
那样做某事)
你有线索或解决办法吗?或者也许我走错了方向?
提前致谢
什么时候 &REST 是 数组?标准说 list。对于关键字参数,这是一个 属性 列表。请参阅 getf
以访问 属性 列表的元素。
也可以使用 DESTRUCTURING-BIND
访问 属性 列表的内容:
CL-USER 15 > (defun foo (a &rest args &key b &allow-other-keys)
(destructuring-bind (&key (c nil c-p) ; var default present?
(d t d-p)
(e 42 e-p)
&allow-other-keys)
args
(list (list :c c c-p)
(list :d d d-p)
(list :e e e-p))))
FOO
; c-p, d-p, e-p show whether the argument was actually present
; otherwise the default value will be used
CL-USER 16 > (foo 10 :b 20 :d 30)
((:C NIL NIL) (:D 30 T) (:E 42 NIL))
但同样可以在参数列表中完成...
我想创建最通用的函数并决定使用键作为参数。
我想使用 allow-other-keys
因为我想使用任何键的功能。
让我告诉你:
(defun myfunc (a &rest rest &key b &allow-other-keys)
;; Print A
(format t "A = ~a~%" a)
;; Print B if defined
(when b
(format t "B = ~a~%" b))
;; Here ... I want to print C or D or any other keys
;; ??
)
(myfunc "Value of A")
(myfunc "Value of A" :b "Value of B")
(myfunc "Value of A" :b "Value of B" :c "Value of C" :d "Value of D")
我知道 rest
是剩余的参数,但它有一个数组。它不绑定值 c
或 d
甚至像关联列表一样构建它们(即像 (cdr (assoc 'c rest))
那样做某事)
你有线索或解决办法吗?或者也许我走错了方向?
提前致谢
什么时候 &REST 是 数组?标准说 list。对于关键字参数,这是一个 属性 列表。请参阅 getf
以访问 属性 列表的元素。
也可以使用 DESTRUCTURING-BIND
访问 属性 列表的内容:
CL-USER 15 > (defun foo (a &rest args &key b &allow-other-keys)
(destructuring-bind (&key (c nil c-p) ; var default present?
(d t d-p)
(e 42 e-p)
&allow-other-keys)
args
(list (list :c c c-p)
(list :d d d-p)
(list :e e e-p))))
FOO
; c-p, d-p, e-p show whether the argument was actually present
; otherwise the default value will be used
CL-USER 16 > (foo 10 :b 20 :d 30)
((:C NIL NIL) (:D 30 T) (:E 42 NIL))
但同样可以在参数列表中完成...