The following MWE behaves unexpectedly (for me):
julia> function f(t)
return t
end
f (generic function with 1 method)
julia> @code_warntype sum(f(1) for i in 1:2)
Variables
#self#::Core.Compiler.Const(sum, false)
a::Base.Generator{UnitRange{Int64},var"#15#16"}
Body::Int64
1 ─ %1 = Base.sum(Base.identity, a)::Int64
└── return %1
It is type stable. However, if I pack this function inside a tuple:
julia> tup = (f, )
(f,)
julia> @code_warntype sum(tup.f(1) for i in 1:2)
Variables
#self#::Core.Compiler.Const(sum, false)
a::Base.Generator{UnitRange{Int64},var"#17#18"}
Body::Any
1 ─ %1 = Base.sum(Base.identity, a)::Any
└── return %1
It becomes type unstable.
What I am trying to accomplish is the following: I have many different functions, which I want to evaluate and add those results:
julia> σ₁(t) = t
σ₁ (generic function with 1 method)
julia> σ₂(t) = 2t
σ₂ (generic function with 1 method)
julia> σ₃(t) = π * t
σ₃ (generic function with 1 method)
julia> σ₄(t) = sin(t)
σ₄ (generic function with 1 method)
julia> σ = (σ₁, σ₂, σ₃, σ₄)
(σ₁, σ₂, σ₃, σ₄)
julia> @code_warntype sum(σ[i](1.0) for i in 1:4)
Variables
#self#::Core.Compiler.Const(sum, false)
a::Base.Generator{UnitRange{Int64},var"#21#22"}
Body::Any
1 ─ %1 = Base.sum(Base.identity, a)::Any
└── return %1
How can I avoid this kind of instability?