Skip to content

Commit

Permalink
add setindex for named tuples (#33468)
Browse files Browse the repository at this point in the history
  • Loading branch information
matbesancon authored and JeffBezanson committed Oct 10, 2019
1 parent 5f013d8 commit 49e2f41
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
24 changes: 24 additions & 0 deletions base/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -300,3 +300,27 @@ function structdiff(a::NamedTuple{an}, b::Union{NamedTuple{bn}, Type{NamedTuple{
NamedTuple{names,types}(map(n->getfield(a, n), names))
end
end

"""
setindex(nt::NamedTuple, val, key::Symbol)
Constructs a new `NamedTuple` with the key `key` set to `val`.
If `key` is already in the keys of `nt`, `val` replaces the old value.
```jldoctest
julia> nt = (a = 3,)
(a = 3,)
julia> Base.setindex(nt, 33, :b)
(a = 3, b = 33)
julia> Base.setindex(nt, 4, :a)
(a = 4,)
julia> Base.setindex(nt, "a", :a)
(a = "a",)
```
"""
function setindex(nt::NamedTuple, v, idx::Symbol)
merge(nt, (; idx => v))
end
8 changes: 8 additions & 0 deletions test/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -267,3 +267,11 @@ let n = NamedTuple{(:T,), Tuple{Type{Float64}}}((Float64,))
@test n isa NamedTuple{(:T,), Tuple{Type{Float64}}}
@test n.T === Float64
end

# setindex
let nt0 = NamedTuple(), nt1 = (a=33,), nt2 = (a=0, b=:v)
@test Base.setindex(nt0, 33, :a) == nt1
@test Base.setindex(Base.setindex(nt1, 0, :a), :v, :b) == nt2
@test Base.setindex(nt1, "value", :a) == (a="value",)
@test Base.setindex(nt1, "value", :a) isa NamedTuple{(:a,),<:Tuple{AbstractString}}
end

0 comments on commit 49e2f41

Please sign in to comment.