Skip to content

Commit

Permalink
more needed functions
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffBezanson committed Jun 4, 2017
1 parent d4bae1a commit 3c72902
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
11 changes: 11 additions & 0 deletions base/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@ endof(t::NamedTuple) = length(t)
getindex(t::NamedTuple, i::Int) = getfield(t, i)
getindex(t::NamedTuple, i::Symbol) = getfield(t, i)

function getindex(t::NamedTuple, I::AbstractVector)
names = unique( Symbol[ isa(i,Symbol) ? i : fieldname(typeof(t),i) for i in I ] )
namedtuple(NamedTuple{(names...)}, [ getfield( t, i ) for i in names ]...)
end

convert(::Type{NamedTuple{names,T}}, itr::NamedTuple{names,T}) where {names,T} = itr

function convert(::Type{NamedTuple{names,T}}, itr) where {names,T}
namedtuple(NamedTuple{names}, T(itr)...)
end

function show(io::IO, t::NamedTuple)
n = length(t)
if n == 0
Expand Down
10 changes: 10 additions & 0 deletions test/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@
@test string((name="", day=:today)) == "(name = \"\", day = :today)"
@test string(NamedTuple()) == "NamedTuple()"

@test hash((a = 1, b = "hello")) == hash(convert(NamedTuple{(:a,:b),Tuple{Int,String}}, (1, "hello")))
@test hash((a = 1, b = "hello")) != hash(convert(NamedTuple{(:a,:c),Tuple{Int,String}}, (1, "hello")))
@test hash((a = 1, b = "hello")) != hash(convert(NamedTuple{(:a,:b),Tuple{Int,String}}, (1, "helo")))

@test (x=4, y=5, z=6)[[1,3]] == (x=4, z=6)
@test (x=4, y=5, z=6)[[:z,:y]] == (z=6, y=5)

@test convert(NamedTuple{(:a,:b),Tuple{Int8,Int16}}, (1,2)) === (a=Int8(1), b=Int16(2))
@test convert(NamedTuple{(:a,:b),Tuple{Int8,Int16}}, (x=3,y=4)) === (a=Int8(3), b=Int16(4))

@test eltype((a=[1,2], b=[3,4])) === Vector{Int}

@test Tuple((a=[1,2], b=[3,4])) == ([1,2], [3,4])
Expand Down

0 comments on commit 3c72902

Please sign in to comment.