奇怪的意外defrecord行为:一个错误或一个功能?

时间:2013-03-23 16:11:36

标签: clojure

;; Once upon a time I opened a REPL and wrote a protocol
;; definition:
(defprotocol SomeProtocol
  (f [this]))

;; And a record:
(defrecord SomeRecord []
  SomeProtocol
  (f [this]
    "I don't do a whole lot."))

;; And a very useful side-effect free function!
(defn some-function []
  (f (SomeRecord.)))

;; I call my function...
(some-function)
;; ...to see exactly what I expect:
;; user=> "I don't do a whole lot."

;; Unsatisfied with the result, I tweak my record a little bit:
(defrecord SomeRecord []
  SomeProtocol
  (f [this]
    "I do a hell of a lot!"))

(some-function)
;; user=> "I don't do a whole lot."

对我来说看起来像个错误。看到之后我才能确定 c ++用户组中的许多错误的编译器错误报告。

1 个答案:

答案 0 :(得分:6)

重新定义记录后,您需要重新定义some-function。这样做的原因是defrecord创建了一个新类型(使用deftype),并且在函数内部使用(SomeRecord.)表示法将代码绑定到该类型,即使在定义了具有相同名称的新类型之后也是如此。这就是为什么它通常更喜欢使用(->SomeRecord)表示法来实例化记录,使用这种表示法将使你的代码像预期的那样工作。

相关问题