Type-stable Array of NamedTuples

As discussed over in Ridiculous idea: types from the future (as @mohamed82008 mentioned), there is a pretty nice way to do this with map:

function f(n)
  map(1:n) do i
    (a=i, b=1.23, c=false, d=:foo)
  end
end

This is a pretty nice solution, since it’s shorter than the original code while being type-stable:

julia> f(5)
5-element Array{NamedTuple{(:a, :b, :c, :d),Tuple{Int64,Float64,Bool,Symbol}},1}:
 (a = 1, b = 1.23, c = 0, d = :foo)
 (a = 2, b = 1.23, c = 0, d = :foo)
 (a = 3, b = 1.23, c = 0, d = :foo)
 (a = 4, b = 1.23, c = 0, d = :foo)
 (a = 5, b = 1.23, c = 0, d = :foo)

julia> @code_warntype f(5)
Variables
  #self#::Core.Compiler.Const(f, false)
  n::Int64
  #3::getfield(Main, Symbol("##3#4"))

Body::Array{NamedTuple{(:a, :b, :c, :d),Tuple{Int64,Float64,Bool,Symbol}},1}
7 Likes