How to qualify some numerical array type as argument

Hi, I’m implementing a function that initializes an array of certain type specified by a type parameter, which I considered using

ArrayInit(ARR::Type{A{V}},siz) where {A<:AbstractArray, V<:Number}

which does not work:

julia> Type{A{V}} where {A<:AbstractArray, V<:Number}
ERROR: TypeError: in Type{...} expression, expected UnionAll, got a value of type TypeVar

So what is the right way of passing something like CuArray{Int} as argument to ArrayInit? In other words, my question is how to qualify ARR as a numerical array type, i.e., ARR<:AbstractArray{T} where T<:Number is true, ARR isa AbstractArray{T} where T is false.

just uses similar

I seem to have found a qualifier as ::Type{AR} where AR<:AbstractArray{V} where V<:Number:

julia> CuArray{Int} isa Type{AR} where AR<:AbstractArray{V} where V<:Number
true

julia> Array{Int} isa Type{AR} where AR<:AbstractArray{V} where V<:Number
true

julia> Tuple{Int} isa Type{AR} where AR<:AbstractArray{V} where V<:Number
false

julia> Array{String} isa Type{AR} where AR<:AbstractArray{V} where V<:Number
false
1 Like

why do you need this ? you don’t have to annotate everything in Julia

To help throwing an error earlier than later into the code

You can use either of these:

ArrayInit(::Type{A}, siz) where {V<:Number, A<:AbstractArray{V}} = A(...)
ArrayInit(::Type{<:AbstractArray{<:Number}}, siz) = ...

The first is for when you need access to the variables A and V, the second is if you just need to restrict inputs.

You don’t have to write ARR::Type{A}, it is A which is your variable.

2 Likes