When using a Set
of a composite type in Julia, the push!
function seems to add duplicate items to the set. Reading the Julia standard documentation, I assumed that the isequal
function would be used to test for duplicates. I guess I misunderstood, so perhaps someone can help me out.
As an example see the code below. In particular, I'd like to know why t2
is added to the set, despite being identical to t1
.
Any help is very much appreciated. Note: In my case two variables of type t
are considered identical if the fields x1
and x2
are equal; the values of the remaining fields do not matter.
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
As DSM indicated, you simply need to add a method for hash
for your type, i.e.:
hash(x::t, h) = hash(x.x2, hash(x.x1, h))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With