Parametric type of parametric type


#1

hi,

how could I define a parametric type of a parametric type, like this:

julia> struct AA{T <: AbstractMatrix{S <: Number} }
           data::T
       end
ERROR: UndefVarError: S not defined
Stacktrace:
 [1] top-level scope at none:0

thanks.


#2

You need S to be a parameter of the type as well:

struct AA{S, T <: AbstractMatrix{S}}
    ...

#3

You can also use a UnionAll constraint:

julia> struct AA{T <: AbstractMatrix{<:Number} }
                  data::T
              end

#4

how do you call it as a “UnionAll” constraint?

struct AA{T <: AbstractMatrix{<:Number} }


#5

I’m not quite sure what you mean. My suggestion is syntactic sugar for

julia> struct AA{T <: AbstractMatrix{T} where T<:Number }
                         data::T
       end

and the constructor just works:

julia> AA([1 2;1 2])
AA{Array{Int64,2}}([1 2; 1 2])

The trick is also useful for method defintions:

f(x::Matrix{<:Number}) = ...

instead of

f(x::Matrix{T} where  T<:Number) = ...

#6

maybe it’s more clear to write as the following?

struct BB{S <: AbstractMatrix{T} where T<:Number }
    data::S
end

#7

If you don’t need the inner type T<:Number within the definition of the struct, what @mauro3 suggests is more concise