【问题标题】:Can I reference other slots in a defstruct?我可以在 defstruct 中引用其他插槽吗?
【发布时间】:2009-02-08 14:33:25
【问题描述】:

在普通的 lisp 中,我注意到我可以这样写:

(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

有没有办法做到这一点?

【问题讨论】:

    标签: common-lisp


    【解决方案1】:

    您可以使用defstruct:constructor 选项来执行此操作。

    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)
    

    有关详细信息,请参阅defstruct 的 CLHS 条目。

    【讨论】:

      【解决方案2】:

      不是这样的。但是你可以使用 Lisp 阅读器技巧:

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

      否则使用defclass 并专门化泛型函数shared-initialize

      请注意,这些阅读器宏将引用 form,而不是评估它的结果。因此

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

      将发出一个thing,其中两个不同的调用generate-unique-id

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        • 2013-06-14
        • 2014-08-10
        • 2011-12-19
        相关资源
        最近更新 更多