Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions base/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,30 @@ length(t::ImmutableDict) = count(Returns(true), t)
isempty(t::ImmutableDict) = !isdefined(t, :parent)
empty(::ImmutableDict, ::Type{K}, ::Type{V}) where {K, V} = ImmutableDict{K,V}()

"""
setindex(d::ImmutableDict, value, key)

Creates a new `ImmutableDict` similar to `d` with the key `key` set to `value`.
If `key` is already in the keys of `d`, `value` replaces the old value.

# Examples
```jldoctest
julia> Base.setindex(Base.ImmutableDict(:a => 1), 2, :a) == Base.ImmutableDict(:a => 2)
true
julia> Base.setindex(Base.ImmutableDict(:a => 1), 2, :b) == Base.ImmutableDict(:a => 1, :b => 2)
true
```
"""
function setindex(d::ImmutableDict, value, key)
Base.ImmutableDict(
(
k => v
for (k, v) in d if k != key
)...,
key => value,
)
end

_similar_for(c::AbstractDict, ::Type{Pair{K,V}}, itr, isz, len) where {K, V} = empty(c, K, V)
_similar_for(c::AbstractDict, ::Type{T}, itr, isz, len) where {T} =
throw(ArgumentError("for AbstractDicts, similar requires an element type of Pair;\n if calling map, consider a comprehension instead"))
Expand Down
4 changes: 4 additions & 0 deletions test/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -907,6 +907,10 @@ import Base.ImmutableDict
@test d6[:b] == 3

@test !haskey(ImmutableDict(-0.0=>1), 0.0)

d7 = ImmutableDict(:a => 1)
@test Base.setindex(d7, 2, :a) == ImmutableDict(:a => 2)
@test Base.setindex(d7, 2, :b) == ImmutableDict(:a => 1, :b => 2)
end

@testset "filtering" begin
Expand Down