Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does push!() adds duplicate elements to a Set?

Tags:

julia

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
like image 557
InkPen Avatar asked Mar 12 '23 10:03

InkPen


1 Answers

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))
like image 162
Scott Jones Avatar answered Mar 21 '23 09:03

Scott Jones