diff --git a/base/exports.jl b/base/exports.jl index 37da399892e43..c4a8083ce3b1f 100644 --- a/base/exports.jl +++ b/base/exports.jl @@ -482,6 +482,7 @@ export firstindex, collect, count, + delete, delete!, deleteat!, eltype, diff --git a/base/namedtuple.jl b/base/namedtuple.jl index fda848e8f66e6..87fcf08b1c981 100644 --- a/base/namedtuple.jl +++ b/base/namedtuple.jl @@ -280,6 +280,24 @@ get(f::Callable, nt::NamedTuple, key::Union{Integer, Symbol}) = haskey(nt, key) (names...,) end +""" + delete(a::NamedTuple, field::Symbol) + +Construct a new named tuple from `a` by removing the named field. + +```jldoctest +julia> delete((a=1, b=2, c=3), :a) +(b = 2, c = 3) + +julia> delete((a=1, b=2, c=3), :b) +(a = 1, c = 3) +``` +""" +function delete(a::NamedTuple{an}, field::Symbol) where {an} + names = diff_names(an, (field,)) + NamedTuple{names}(a) +end + """ structdiff(a::NamedTuple{an}, b::Union{NamedTuple{bn},Type{NamedTuple{bn}}}) where {an,bn} diff --git a/test/namedtuple.jl b/test/namedtuple.jl index 2d1885963f3d6..49cf825ba16e2 100644 --- a/test/namedtuple.jl +++ b/test/namedtuple.jl @@ -201,6 +201,11 @@ end abstr_nt_22194_3() @test Base.return_types(abstr_nt_22194_3, ()) == Any[Any] +@test delete((a=1,), :a) == NamedTuple() +@test delete((a=1, b=2), :a) == (b=2,) +@test delete((a=1, b=2, c=3), :b) == (a=1, c=3) +@test delete((a=1, b=2, c=3), :z) == (a=1, b=2, c=3) + @test Base.structdiff((a=1, b=2), (b=3,)) == (a=1,) @test Base.structdiff((a=1, b=2, z=20), (b=3,)) == (a=1, z=20) @test Base.structdiff((a=1, b=2, z=20), (b=3, q=20, z=1)) == (a=1,)