Skip to content

setindex!! turns an OrderedDict to a Dict #42

Description

@mhauru
julia> typeof(setindex!!(OrderedDict{Union{},Union{}}(), 0, 4))
Dict{Int64, Int64}

This only happens if the key or element type needs widening. Not sure what the solution here is. Maybe OrderedCollections needs a BangBang extension?

Later...

Just tried to understand this a bit better, and the culprit method is this, which reads

function _setindex(d0::AbstractDict, v, k)
    K = promote_type(keytype(d0), typeof(k))
    V = promote_type(valtype(d0), typeof(v))
    d = Dict{K, V}()
    copy!(d, d0)
    d[k] = v
    return d
end

This feels quite funny to me: Any AbstractDict, under non-mutating _setindex, is just straight-up changed to a Dict.

What's the interface that every AbstractDict type must implement? Is it documented somewhere? I can't find it.

If it includes merge, and it might, then we could do

function _setindex(d0::AbstractDict, v, k)
    return merge(d0, basetypeof(d0)(k => v))
end

where basetypeof gets the type of d0 stripped of type parameters (I forget now how to do it).

Or we could do something like

function _setindex(d0::AbstractDict, v, k)
    K = promote_type(keytype(d0), typeof(k))
    V = promote_type(valtype(d0), typeof(v))
    d = basetypeof(d0){K,V}(k => v)
    for k0, v0 in items(d0)
        d[k0] = v0
    end
    return d
end

although I'm not sure what basetypeof(d0){K,V} there means, because even though every AbstractDict type must have a K and V type parameter, they don't need to be the first two type parameters.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions