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 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}
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.