I am new to Julia and I am not sure why the last line evaluates to false:
type Point{T}
x::T
y::T
end
D = [Point(1.,2.) => 42]
haskey(D, Point(1., 2.)) #False!
Clearly the key exists so what's going on here!?
Edit.
If I don't use a class Point, it works fine:
D = [(1.,2.) => 42]
haskey(D, (1., 2.)) #True!
Can we not use classes for dictionary key types?
But look at this:
type Point{T}
x::T
y::T
end
P = Point(1., 2.)
D = [P => 42]
haskey(D, P)
evaluates to true.
It does work if you use the same object, but it does not work if you use 2 objects with the same field values. Note that objects defined using type are mutable, so even after you used a Point as a key, you could have still changed the values of its fields without the dictionary knowing. The dictionary needs to hash on something that cannot change, like a type-object's identity, and not it's field values of the moment. Since tuples are immutable their values can be safely used as keys. You could also use
immutable Point{T}
x::T
y::T
end
If you define a custom hash method for Point, then things will work as you expect.
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