Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia's dictionary method `haskey` returning false when key is present

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?

like image 527
anthonybell Avatar asked Jan 17 '26 06:01

anthonybell


2 Answers

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    
like image 184
Christopher Ian Stern Avatar answered Jan 19 '26 18:01

Christopher Ian Stern


If you define a custom hash method for Point, then things will work as you expect.

like image 41
tholy Avatar answered Jan 19 '26 20:01

tholy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!