Skip to content

Commit c10868e

Browse files
committed
Implement setindex for Base.ImmutableDict
The design of Base.ImmutableDict allows the same key to be added again, which shadows the previously added value. Unfortunately, it still prints out all of the entries, including repeated keys. I thought this might be confusing, so I implemented it to remove the value if the key exists and then add the new value. Closes #216
1 parent 4e3d9e5 commit c10868e

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

src/setindex.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ Base.@propagate_inbounds function setindex(d0::AbstractDict, v, k)
2424
return d
2525
end
2626

27+
function setindex(d::Base.ImmutableDict, v, k)
28+
Base.ImmutableDict(d, k => v)
29+
end
30+
2731
# may be added to Base in https://github.com/JuliaLang/julia/pull/46453
2832
@inline function setindex(t::Tuple, v, inds::AbstractVector{<:Integer})
2933
ntuple(length(t)) do i

test/test_setindex.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@ end
4343
@test Accessors.setindex(d, 30, "c") ==Dict(:a=>1, :b=>2, "c"=>30)
4444
@test Accessors.setindex(d, 10.0, :a) ==Dict(:a=>10.0, :b=>2.0)
4545

46+
d = Base.ImmutableDict(:a => 1, :b => 2)
47+
@test @set(d[:a] = 3) == Base.ImmutableDict(:a => 1, :b => 2, :a => 3)
48+
@test @set(d[:c] = 3) == Base.ImmutableDict(:a => 1, :b => 2, :c => 3)
49+
4650
nt = (a=1, b='2')
4751
@test @set(nt[:a] = "abc") == (a="abc", b='2')
4852
@test @set(nt[1] = "abc") == (a="abc", b='2')

0 commit comments

Comments
 (0)