Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
immutable DefaultDict{K, V} <: Associative{K, V}
dict::Dict{K, V}
default::V
end
function DefaultDict(val)
return DefaultDict(Dict(), val)
end
function Base.getindex{K, V}(dd::DefaultDict{K, V}, key::K)
if haskey(dd.dict, key)
getindex(dd.dict, key)
else
dd.default
end
end
Base.convert(::Type{Associative}, dd::DefaultDict) = dd.dict
Base.promote_rule(::Type{Associative}, ::Type{DefaultDict}) = Associative
#= Why don't we get these for free with `convert` and `promote_rule`?
Base.setindex!{K, V}(dd::DefaultDict{K, V}, key::K, val::V) = setindex!(dd.dict, key, val)
Base.length(dd::DefaultDict) = length(dd.dict)
=#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.