1

I'm trying to define a custom equality method for a new type I've constructed. This is a MWE getting at what I'm trying to do.

mutable struct a
    first_num::Int
    second_num::Int
end

import Base.==
import Base.hash
function hash(obj::a, h=33141651)
    return hash((obj.first_num, obj.second_num), h)
end

function ==(obj1::a, obj2::a)
    if hash(obj1) == hash(obj2)
        return true
    else
        return false
    end
end

a1 = a(2,3)
a2 = a(2,3)
a1 == a2

I then get an error like ERROR: TypeError: ==: in typeassert, expected UInt64, got Int64

Is h becoming Int64?

In addition, if hashing the tuple of attributes is simply not the correct way to do this, let me know.

Edit: Actually, I ran this and I'm getting MethodError: no method matching hash(::Tuple{Int64,Int64}, ::Int64). Is h being promoted to Int64?

1
  • I hope you're not assuming that hash(obj1) == hash(obj2) means that obj1 == obj2, because that's just not true in the general case. Two objects can return the same hash code, but not be equal. Commented Apr 27, 2018 at 13:23

1 Answer 1

4

The problem is that your literal value for h (33141651) is an Int rather than a UInt. Thus, when you call hash with the tuple h is an Int, but the internal tuple hash function expects a UInt. I don't think you have to specify a value for h at all, and something like this should be enough:

function Base.hash(obj::a, h::UInt)
    return hash((obj.first_num, obj.second_num), h)
end

Full example for completeness:

mutable struct A
    first::Int
    second::Int
end

function Base.hash(obj::A, h::UInt)
    return hash((obj.first, obj.second), h)
end

function Base.:(==)(obj1::A, obj2::A)
    return hash(obj1) == hash(obj2)
end

With the following behaviour

julia> a = A(2,3); b = A(2,3)
A(2, 3)

julia> hash(a)
0x965b43497b212144

julia> hash(b)
0x965b43497b212144

julia> a == b
true
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.