Strange unexpected behavior of defrecord: error or function?

;; 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." 

Looks like a mistake. I just can't be sure to see a lot of false compiler error reports in a C ++ user group.

+4
source share
1 answer

You need to override some-function after redefining the entry. The reason for this is that defrecord creates a new type (using deftype), and using notation (SomeRecord.) Inside the function will bind code to this type even after a new type with the same name is defined. This is why it is generally recommended that you use a notation (->SomeRecord) to instantiate an entry using this notation so that your code works as you expect.

+6
source

All Articles