Type stability when arguments are functions

Try “lispy tuple recursion,”

@inline g2(fs::Tuple{Function, Vararg{Function}}, x::Float64) = _g2(0.0, fs, x)
# _gs is a "private" method that processes the first call, then discards that function and recursively calls itself 
@inline _g2(a, fs::Tuple{Function, Vararg{Function}}, x::Float64) = _g2(a + fs[1](x), Base.tail(fs), x)
# But we have to terminate the recursion. This method is called when we've "used up" all the functions
_g2(a, ::Tuple{}, x::Float64) = a

@code_warntype g2((sin, cos, tan), 3.14)

You’ll see this is type-stable even without any of the type-assertions/declarations.

6 Likes