function f(x)
if x < 0
return 0
end
return expensive_function(x)
end
Is not type-stable (in most cases). Is there a clean way to make it stable and generic, while staying performant for x < 0 ? The most straightforward thing I see would be to replace return 0 with
return zero(expensive_function(x))
but this does evaluate expensive_function(x) as far as I can tell.
I saw in this question, that it is not easy to get the return type of a function without evaluating it. Now I don’t want to use the type in the code, I just want f to be type stable and performant for x < 0. Is this possible, assuming expensive_function(x) is type-stable?
But if you really need to get a zero of the same type as expensive_function then you need some way to calculate the resulting element type yourself.
Could I do this with a generated function? Something like:
@generated function f(x)
expensive_type = typeof(expensive_function(zero(x)))
quote
if x < 0
return zero($expensive_type)
end
return expensive_function(x)
end
end
I did that before posting because I was indeed suspicious and I know generated functions should be used sparingly and with caution, but I couldn’t put my finger on any concrete problem with the code.
I thought about if it observes any global mutable state, but it just calls some functions and the docs just mention “Calling any function that is defined after the body of the generated function” as bad, which to me sounds like calling other functions is ok.
So as far as I can see, the code does nothing that the docs forbid. Or am I missing something?