-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unexpected behavior of get!(f::Function, collection, key) #9573
Comments
I vote for 1. I don't see a compelling reason to support a default that changes the dictionary. |
It can occur when you use memoization. Consider the following basic example: cache1 = Dict{Int, BigInt}()
cache2 = Dict{Int, BigInt}()
function fib1(n::Int)
@assert n >= 0
get!(cache1, n) do
return n == 0 ? BigInt(1) : BigInt(n) * fib1(n - 1)
end
end
function fib2(n::Int)
@assert n >= 0
if n in cache2
return cache2[n]
end
v = n == 0 ? BigInt(1) : BigInt(n) * fib2(n - 1)
cache2[n] = v
return v
end
println(fib1(50))
println(length(cache1)) # should be 51
println(fib2(50))
println(length(cache2)) # is 51 which produces
And we wee that using |
Indeed, if we didn't intend option (1), this function would not even exist. The only purpose of it is performance. Another option is to add an internal |
makes `get!` work with default functions that modify the dict. fixes #9573
Dup of #7944 |
makes `get!` work with default functions that modify the dict. fixes #9573
makes `get!` work with default functions that modify the dict. fixes JuliaLang#9573
makes `get!` work with default functions that modify the dict. fixes JuliaLang#9573
Function
get!(f::Function, collection, key)
makes the following steps in case key is not found in the dictionary:index = ht_keyindex2(h, key)
v = convert(V, default())
_setindex!(h, v, key, -index)
This sequence might produce wrong results if
default()
changes the underlying dictionary.Possible solutions:
default
may not change the dictionary;_setindex!(h, v, key, -index)
toh[k] = v
(this would reduce the performance ofget!
because we have to calculate index twice);get!
definitionget!{K,V}(default::Callable, h::Dict{K,V}, key0; stable::Bool=false)
, wherestable
indicates thatdefault
does not change the dictionary (and isfalse
by default) and using this parameter execute appropriate code.The text was updated successfully, but these errors were encountered: