Suppose I have a function such as:
function f(x::Int,y::Float64)::Real
return y^x
end
Is there a way to get the domain type from this function (and possibly the "codomain", which in this case was ::Real)? I'm supposing that this function has only one method. And in case there are many, one can just take the first method asfirst(methods(f))
.
I wish to get something like Tuple{Int,Float64}
for the domain type, and Real
for the codomain.
P.S: I already have a macro that can do this during the function declaration, but I was wondering if one can do it after the function is already declared.
Are you talking about looking things up in the method table?
methods(f).sig not sure about annotated return type
annotated return types just insert a convert
at return points, it doesn't show up in the method signature (that's inference' domain)
in general, you'll need to know the input types to your method to get the output type(s) (there may be multiple for type unstable functions)
It also inserts a typeassert, right? But yeah okay
yes
After the convert, yeah
Thanks for the replies! Here is the solution I came up with. Feel free to tell me how to improve it:
function getfunctiontype(f, methodindex=1)
m = collect(methods(f))[methodindex]
dom = Tuple([m.sig.types[2:end]...])
codom = Base.code_typed(f, dom)[1].second
if length(dom) == 1
dom = dom[1]
end
return dom,codom
end
This if length(dom) == 1
is ugly, but I don't know how to avoid it.
Do you need it? Isn't it better to return a Tuple
in all cases, do you need a special check for the one argument case?
Just for curiosity, why are you willing to get these signatures? That feels like a XY problem, unless you are doing something very low level.
Sundar R said:
Do you need it? Isn't it better to return a
Tuple
in all cases, do you need a special check for the one argument case?
I wrote a composition that is restricted on types, so Tuple{Int} == Int
fails. Hence, I either fix this here or in the composition implementation.
I thought fixing here would be better cause it then returns the actual types.
Davi Sales Barreira has marked this topic as resolved.
Last updated: Dec 28 2024 at 04:38 UTC