Type unstability with args

Hello,

I would like to make the following function type stable:

function f(args…)
t = Tuple([arg] for arg in args)
return t
end

f(1,2.0,“s”)

a run from @code_warntype gives me

julia> @code_warntype f2(1,2.0,“s”)
MethodInstance for f2(::Int64, ::Float64, ::String)
from f2(args…) @ Main REPL[40]:1
Arguments
#self#::Core.Const(Main.f2)
args::Tuple{Int64, Float64, String}
Locals
#25::var"#25#26"
t::Tuple{Vararg{Vector}}
Body::Tuple{Vararg{Vector}}
1 ─ %1 = Main.Tuple::Core.Const(Tuple)
│ %2 = Main.:(var"#25#26")::Core.Const(var"#25#26")
│ (#25 = %new(%2))
│ %4 = #25::Core.Const(var"#25#26"())
│ %5 = Base.Generator(%4, args)::Base.Generator{Tuple{Int64, Float64, String}, var"#25#26"}
│ (t = (%1)(%5))
│ %7 = t::Tuple{Vararg{Vector}}
└── return %7

The type of args is inferred correctly. I thought it would be enough to guess the correct type of t but somehow there is a Vararg which pops up.

Any help would be appreciated.

The issue is that looping over the tuple results in the element type being inferred as Any. (that could possibly be changed, to be fair).
So, instead of using a for loop, you can access the tuple elements in a different manner. For example, here, I access them by indexing:

function f(args...)
    ntuple(length(args)) do i
        [args[i]]
    end
end

This is type stable.

2 Likes

Thank you very much it works !
I was not aware of this method to create ntuple.

map should be type stable too

map(args) do x
    [x]
end