2009-02-08 53 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

相关问题