为什么push!()会向一个Set添加重复的元素?

Ink*_*Pen 4 julia

Set在Julia中使用复合类型时,该push!函数似乎将重复项添加到集合中.阅读Julia标准文档,我假设该isequal函数将用于测试重复项.我想我误解了,所以也许有人可以帮助我.

作为示例,请参阅下面的代码.特别是,我想知道为什么t2添加到集合中,尽管与之相同t1.

很感谢任何形式的帮助.注:在我的情况类型的两个变量t被认为是如果字段相同x1x2相等; 其余字段的值无关紧要.

type t 

  x1::Float64
  x2::Float64

  b1::Bool
  b2::Bool

end

isequal( tx::t, ty::t) = (tx.x1 == ty.x1) && (tx.x2 == ty.x2)
==(tx::t, ty::t)       = (tx.x1 == ty.x1) && (tx.x2 == ty.x2)

t1 = t( 1, 2, true, true)
t2 = t( 1, 2, true, true)
tc = t1
tdc = deepcopy( t1)

[ t1 == t2   isequal( t1, t2)]  # ---> [ true true ]
[ t1 == tc   isequal( t1, tc)]  # ---> [ true true ]
[ t1 == tdc  isequal( t1, tdc)] # ---> [ true true ]


s = Set{t}()
push!( s, t1) 
push!( s, t2) # adds t2 to the set although t2 and t1 are identical ...
push!( s, tc) # does not add ...
push!( s, tdc) # adds tdc although tdc and t1 are identical
Run Code Online (Sandbox Code Playgroud)

Sco*_*nes 7

如DSM所示,您只需hash为您的类型添加方法,即:

hash(x::t, h) = hash(x.x2, hash(x.x1, h))
Run Code Online (Sandbox Code Playgroud)