在普通的lisp中使用&allow-other-keys

Sma*_*isp 6 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")
Run Code Online (Sandbox Code Playgroud)

我知道这rest是剩下的args,但它有一个数组.它不绑定值c,d甚至不像关联列表那样构建它们(即做某事(cdr (assoc 'c rest)))

你有线索或解决方案吗?或者我可能走向错误的方向?

提前致谢

Rai*_*wig 8

从什么时候开始,REST是一个数组?标准说清单.在关键字参数的情况下,这是属性列表.请参阅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))
Run Code Online (Sandbox Code Playgroud)

但是已经可以在参数列表中完成同样的工作......

  • 好的......我很糟糕.`:C`.傻我.谢谢,@ lainer (2认同)