Capture part of return type

Is there a way to capture the type of a return in a variable (specifically a parameter of the variable type, but baby steps)

function f()
    A::AbstractArray{T} where T = [1.0 2.0]
    return T
end

Of course I can pretty easily get this info otherwise, but this syntax almost seems like it makes sense. Almost, because it’s not quite clear how you’d get the scoping to work.

edit: Honestly, I’d also be happy with hearing about some non-syntactic way to say something like

@get_type T AbstractArray{T} typeof(A)

where it pattern matches and sets the T variable.

edit 2: … is the answer just to use function dispatch? That’s the answer, isn’t it. Sorry for the noise.

Are you just looking for eltype?

julia> A = [1.0, 2.0]
2-element Array{Float64,1}:
 1.0
 2.0

julia> T = eltype(A)
Float64
3 Likes

Not quite. I’m actually doing more like nt::NamedTuple{names} = (a = 1.0, b = 2.0). But this works for my particular purposes:

typenames(nt::NamedTuple{names}) where names = names

It’d be nice if there were a simple syntactic way to do this, but writing a little helper function is fine

1 Like

I could be wrong but it seems you could write a macro which lets you have the syntax from your OP by creating the helper function you, and it could probably be pretty generic. Ie it would turn,

function f()
    A::AbstractArray{T} where T = [1.0 2.0]
    return T
end

into

function f()
    A::AbstractArray{T} where T = [1.0 2.0]
    T = ((::AbstractArray{T} where T)->T)(A)
    return T
end

And you can imagine this kind of thing can be done pretty programatically. Just an idea.

I am afraid I still don’t understand the question, but would

julia> keys((a = 1, b = 2))
(:a, :b)

help?

Also fieldnames in type space.

1 Like