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?
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:
hashindex).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.
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