function fun(idx, a::Int, b::Int)
funs = [+, -]
return funs[idx](a, b)
end
Is not type-stable because Julia does not infer the return type of funs[idx]. Here is the output of @code_warntype fun(1, 2, 3):
MethodInstance for fun(::Int64, ::Int64, ::Int64)
from fun(idx, a, b) @ Main
Arguments
#self#::Core.Const(fun)
idx::Int64
a::Int64
b::Int64
Locals
funs::Vector{Function}
Body::Any
1 β (funs = Base.vect(Main.:+, Main.:-))
β %2 = Base.getindex(funs, idx)::Function
β %3 = (%2)(a, b)::Any
βββ return %3
Say that I know the return type will always be Int64. Is there an annotation, or parametric type for funs that will tell the compiler that? Is there another way to help the compiler infer the return type in similar cases?
import FunctionWrappers: FunctionWrapper
function fun(idx, a::Int, b::Int)
funs = FunctionWrapper{Int64, Tuple{Int64, Int64}}[+, -]
return funs[idx](a, b)
end
@code_warntype fun(1, 3, 5)
Not a lot of documentation available, but I think itβs used quite extensively across the Julia ecosystem. Hopefully someone else can fill any technical details.