I have a type-stable function f(x) that is expensive to evaluate. Given an argument x, how do I obtain the type of the result f(x), but without actually evaluating f(x)?
Ideally this should be elided during compilation and there should be no computation at all, because the type of f(x) is known at compile time.
This should generally behave the way that you want, but be aware that it generally has the liberty to return Any, return different results, etc. If there’s any other way to do what you want it’s probably a good idea.
I second this. These “other ways” are documented mostly in the source of Julia and the standard libraries though. A more specific question would allow suggesting the right one.
Eg if you are collecting things, I would recommend you look at the functions collect calls, or a functional approach I experimented with.
Core.Compiler.return_type(gcd, Tuple{Int,Int}) is the only function that is useful for this in the very few case you are allowed to use it. Don’t use code_typed.
In general, you don’t. But it’s reasonable to expect that exp(x), x/1 and float(x) will have the same type, and if someone defines exp to return a string or something then I say that’s on them.
(In any case, the worst that happens here is that you get a union, which is no longer that big of a deal for performance anyway.)