How to define a parametric struct variable which could be an array or a scalar?

Depending on the inputs x, P, F of a function test the output can be of type array or scalar:

struct Results{A <: Union{Float64, <: AbstractVector{Float64}}, B <: Union{Float64, <: AbstractMatrix{Float64}}}
    a::A
    b::B
end  
function test(x, P, F)
    Results(F * x, F * P * F')
end
julia> test([1., 0.], [1. 0.; 0. 1.], [1. 0.; 0. 1.])
Results{Array{Float64,1},Array{Float64,2}}([1.0, 0.0], [1.0 0.0; 0.0 1.0])
julia> test([1., 0.], [1. 0.; 0. 1.], [1., 0.]')
Results{Float64,Float64}(1.0, 1.0)

This works. However, Iā€™d like Float64 to be parametric. Simply replacing Float64 with T does not work:

struct Results{A <: Union{T, <: AbstractVector{T}}, B <: Union{T, <: AbstractMatrix{T}}}
    a::A
    b::B
end

This results in: ERROR: UndefVarError: T not defined

You would make T the first type parameter.

That said, I would not worry about it, and just define

struct Results{A,B}
    a::A
    b::B
end

and dispatch on them accordingly.

3 Likes