Open
Description
I need a good way to both test for a value in a dictionary and get that value, without resorting to one of the following fallbacks, all of which are somewhat undesirable:
get(dict, key, specialnullval)
-- problematic because I must either use a separate type to represent null (inefficient due to the type-variadic return), or I must have some special way to represent null within the value type of the dictionary.haskey(dict, key)
followed bydict[key]
-- problematic because it looks up the key twice when it exists.try k = dict[key] catch ...
-- problematic because it relies on exceptions when the key is not present.
It seems that all of this can be solved my making use of Julia v0.4's Nullable
type, with something like the following:
function getnull{K,V}(h::Dict{K,V}, key)
index = ht_keyindex(h, key)
return (index<0) ? Nullable{V}() : Nullable{V}(h.vals[index]::V)
end
I am proposing that this be included as part of base/dict.jl
, possibly under a different/better name.
Is there some other/better way to do this?