2009-02-08 52 views
5

Common Lisp中我注意到,我可以這樣寫:我可以參考defstruct中的其他插槽嗎?

(defun foo (&key (a 1) (b 2) (c (+ a b))) (print (+ a b c))) 

當我打電話(foo),打印6。所以參數c可以參考爲ab設置的值。但我似乎無法找到與defstruct類似的方法。例如:

CL-USER> (defstruct thing a b c) 
THING 
CL-USER> (setq q (make-thing :a 1 :b 2 :c (+ a b))) 
; Evaluation aborted 
CL-USER> (setq q (make-thing :a 1 :b 2 :c (+ :a :b))) 
; Evaluation aborted 

有沒有辦法做到這一點?

回答

7

您可以使用:constructor選項defstruct來執行此操作。

CL-USER> (defstruct (thing 
         (:constructor make-thing (&key a b (c (+ a b))))) 
      a b c) 
THING 
CL-USER> (make-thing :a 1 :b 2) 
#S(THING :A 1 :B 2 :C 3) 

欲瞭解更多信息,請參閱CLHS條目defstruct

+0

啊,這好像是我所希望的......謝謝! – casper 2009-02-12 22:39:11

3

並非如此。但是,使用Lisp的讀者的技巧,你可以這樣做:

(make-thing :a #1=1 :b #2=2 :c (+ #1# #2#)) 

否則使用defclass和專門的通用功能shared-initialize

請注意,這些閱讀器宏將引用表格,而不是評估它的結果。因此

(make-thing :id #1=(generate-unique-id) :my-id-is #1#) 

會讓thing兩個不同調用generate-unique-id

相關問題