AbstractArray and Vector of AbstractArray as an input

Hi,
I’m testing how the AbstractArray works as an input type declaration. When I defined two functions as follows, test1 worked just fine but test2.
Is test2 type declaration invalid? Or, the way to call the function is wrong?

julia> T = AbstractArray{T, 2} where T <: Union{Float32, Float64}

julia> test1(::T) = pritnln("I'm not a vector.")

julia> test2(::Vector{T}) = println("I'm a vector.")

julia> v = [1.0 2.0; 3.0 4.0]

julia> test1(v)
I'm not a vector.

julia> test2([v])
ERROR: MethodError: no method matching test2(::Vector{Matrix{Float64}})

Closest candidates are:
  test2(::Vector{AbstractMatrix{T} where T<:Union{Float32, Float64}}) 

You need

test2(::Vector{<:T}) = println("I'm a vector.")

because the element type of [v] is not exactly T. Then

julia> test2([v])
I'm a vector.
2 Likes

Thank you very much! It’s clear now. I confirmed that test3 and test5 work since T1 is nontrivial but T2 isn’t.

julia> T1 = Array{Float64, 2}

julia> T2 = Array{T, 2} where T <: Union(Float32, Float64}

julia> test3(::Vector{T1}) = println("Works!")

julia> test4(::Vector{T2}) = println("Not work")

julia> test5(::Vector{<:T2}) = println("Works!")

julia> test3([v])
Works!

julia> test4([v])
ERROR...

julia> test5([v])
Works!

You can also explicitly specify the element type of a vector. For example, T2[v] has element type T2, and test4(T2[v]) works. (However, a non-concrete element type is usually not a good idea.)

BTW, I had to change the definition of T2 to

T2 = Array{T, 2} where T <: Union{Float32, Float64}

Thanks. I correct my code. I’ve also tried this.

julia> T2 = Array{T, 2} where T <: Union{Float32, Float64}

julia> test4(::Vector{T2}) = println("Not work")

julia> v = [1.0 2.0; 3.0 4.0]

julia> vv = Vector{T2}(undef, 0)

julia> for n in 1:3
             push!(vv, v)
         end

julia> test4(vv)
Not work

The easiest way to create an empty vector of type T2 is to say T2[]. In any case, if one creates a vector by adding elements to an empty vector, then it’s important to specify the element type, as you did. The empty list [] has element type Any, and that would lead to very slow code.