2015-11-25 23 views
3

我想製作最通用的函數,並決定使用鍵作爲參數。 我想使用allow-other-keys,因爲我想用任何鍵使用該功能。在普通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是剩餘ARGS,但它有一個數組。它不綁定值cd或者甚至像關聯列表一樣構建它們(即,像做(cdr (assoc 'c rest))那樣做)

您是否有線索或解決方案?或者我可能走錯了方向?

預先感謝

回答

5

由於當爲& 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)) 

但同樣可能已經在參數列表中已經做...

+0

很抱歉的類型混淆。是的,這是一個清單,你是絕對正確的。我會看看'getf'在我的情況。感謝您的回答。 – SmartyLisp

+0

我仍然感到困惑,因爲'rest'有這樣的值:'(C的D值的值)'但是'(getf rest'c)'或'(getf rest'C)'給我'NIL' – SmartyLisp

+2

好的。 .. 我的錯。 ':C'。傻我。謝謝,@rainer – SmartyLisp