Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dict with array key in julia

In julia language (ver 1.1.0), I am experimenting what would happen when I mutate a dictionary key.

Before mutation, both the variable x and [1,2,3] is recognized.

x = [1,2,3]; d = Dict(x=>"x")
haskey(d, x)
# true

haskey(d, [1,2,3])
# true

Once I mutate x, neither the variable x nor [1,2,3,4] is recognized.

push!(x, 4)
haskey(d, x)
# false

haskey(d, [1,2,3,4])
# false

haskey(d, [1,2,3])
# false

Value-wise, the key is "equal" to x, so I guess this has something to do with the hash function, but could not understand the source code.

collect(keys(d))[1] == x == [1,2,3,4]
# true

Can someone explain what makes this behavior, or suggest resources that I should look at?

like image 604
Kota Mori Avatar asked Dec 01 '25 05:12

Kota Mori


1 Answers

The key function to look into is ht_keyindex.

There you can see that in order for the key to be found it must both:

  • Match hash value (via hashindex).
  • Match identity or value.

There is a non-negligible probability that after mutating x it will have the same hashindex value and the key would be found. For example here you could set index 4 of x to 5 and all seemingly would work:

julia> x[4] = 5
5

julia> x
4-element Array{Int64,1}:
 1
 2
 3
 5

julia> haskey(d, x)
true

Therefore - as in any programming language supporting dictionaries in a similar way - mutating keys of the dictionary should not be done. The above discussion should be in practice only a theoretical one.

like image 192
Bogumił Kamiński Avatar answered Dec 04 '25 01:12

Bogumił Kamiński



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!