Clojure值相等和集合

Mar*_*rio 4 clojure set

如果我有一个自定义类型,并且我用它创建两个具有完全相同值的独立实例,我可以使用什么方法来确定这两个东西是等价的? identical?并=和==似乎并不管用.我本来期望有一些协议来设置类型比较.最终,我希望它能够在一组中添加相同的东西.

(deftype Ref [id])
(def r1 (->Ref 1))
(def r2 (->Ref 1))
(= r1 r2) ;false rather than true
(def refs #{})
(conj refs r1 r2) ;adds both, but want one
Run Code Online (Sandbox Code Playgroud)

=有工作defrecord,但我会如何定义=的deftype?

Ale*_*ler 7

在你的deftype中,扩展Object并实现equals它们以赋予它们相等的语义:

(deftype Ref [id]
  Object
  (equals [_ other] (= id (.id other))))
Run Code Online (Sandbox Code Playgroud)

设置包含也需要哈希码支持:

(deftype Ref [id]
  Object
  (equals [_ other] (= id (.id other)))
  (hashCode [_] id) 
  clojure.lang.IHashEq 
  (hasheq [_] id))
Run Code Online (Sandbox Code Playgroud)

我在那里实现了Java哈希支持和Clojure hasheq支持.实现IHashEq会更快.


noi*_*ith 5

defrecord 已经有你描述的这种行为:

user=> (defrecord Point [x y])
user.Point
user=> (= (Point. 0 0) (Point. 0 0))
true
user=> (into #{} [(Point. 0 0) (Point. 1 1) (Point. 0 0)])
#{#user.Point{:x 1, :y 1} #user.Point{:x 0, :y 0}}
Run Code Online (Sandbox Code Playgroud)

deftype另一方面,默认情况下没有实现Clojure通常的结构相等性(也没有defstruct给出我们的可读打印方法):

user=> (deftype Pair [a b])
user.Pair
user=> (= (Pair. 0 0) (Pair. 0 0))
false
user=> (into #{} [(Pair. 0 0) (Pair. 1 1) (Pair. 0 0)])
#{#<Pair user.Pair@5de3182> #<Pair user.Pair@6497d63> #<Pair user.Pair@38eed810>}
Run Code Online (Sandbox Code Playgroud)

也就是说,deftype功能更强大,你可以按照我们喜欢的方式行事:

user=> (deftype Tuple [a b]
         Object
         (equals [this other]
           (and (= (.a this) (.a other))
                (= (.b this) (.b other))))
         (toString [this]
           (str "<" (.a this) "," (.b this) ">"))
         (hashCode [this]
           (hash {:a (.a this) :b (.b this)}))
         Comparable
         (compareTo [this that]
           (compare [(.a this) (.b this)]
                    [(.a that) (.b that)])))
user.Tuple
user=> (= (Tuple. 0 0) (Tuple. 0 0))
true
user=> (into #{} [(Tuple. 0 0) (Tuple. 1 1) (Tuple. 0 0)])
#{#<Tuple <0,0>> #<Tuple <1,1>>}
Run Code Online (Sandbox Code Playgroud)