Merging dictionaries indexed by elements of struct type

Hello, I am failing merging correctly dictionaries that are indexed by a mutable struct that I defined before. Here is the code of a baby example :

mutable struct my_vector
v::Vector{Int}
end

Base.:(==)(v1::my_vector,v2::my_vector) = (v1.v==v2.v)
Base.isequal(v1::my_vector,v2::my_vector) = (v1.v==v2.v)

v1=my_vector([1,2])
v2=my_vector([1,2])

d1=Dict([(v1,1)])
d2=Dict([(v2,1)])
println(merge(+,d1,d2)) # Dict(my_vector([1, 2])=>1,my_vector([1, 2])=>1)

D1=Dict([([1,2],1)])
D2=Dict([([1,2],1)])
println(merge(+,D1,D2)) # Dict([1, 2]=>2)

I would like to know if it is possible to correct the code so that the output on the first line would be
Dict(my_vector([1, 2])=>2)

Thanks for your help ! :wink:

It looks like you’re missing a definition of Base.hash for your type. From the documentation for isequal (which you can read by typing ?isequal):

isequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).

Since your isequal and == tests just check the v member, you can do the same for hashing:

julia> Base.hash(v::my_vector, seed::UInt) = hash(v.v, seed)

Also, please quote your code so that it is easier to read. You can find some helpful instructions on how to do that here: PSA: make it easier to help you

2 Likes

Thanks ! This is exactly what I needed.