aberdysh
aberdysh

Reputation: 1664

Strange behaviour of a type assert

For simplicity's sake, suppose I have the following function defined:

function returnVectorOrMatrix()
    vals = Array(Array{Float32,1}, 10)   # vector in this definition
    return vals::Array{Array{Float32},1}
end

arr = returnVectorOrMatrix()

Which to my big surprise generates the following error:

ERROR: type: typeassert: expected Array{Array{Float32,N},1},
got Array{Array{Float32,1},1}

Does anyone have a good logical reasoning as to why this is happening / was designed in such way? Because Array{Array{Float32,1},1} is just a special case of Array{Array{Float32,N},1} with N = 1 so given that Julia is multiple-dispatch I would expect such function to work fine (and seems logical/intuitive as well)

Upvotes: 1

Views: 188

Answers (2)

Scott Jones
Scott Jones

Reputation: 1750

I think the problem is simply that Array{Float32} is really Array{Float32,N}, and not Array{Float32,1} (which is the same as Vector{Float32}).

Upvotes: 0

Gnimuc
Gnimuc

Reputation: 8566

Hint:

julia> Array{Float32,1} <: Array{Float32}
true

julia> Array{Array{Float32,1},1} <: Array{Array{Float32},1}
false

julia> Array{Array{Float32,1},1} <: Array{Array{Float32,1}}
true

could you find any clue now?

in fact, the Array{Array{Float32,1},1} is a parametric type,

julia> Array{Array{Float32,1},1} <: Array{Array{Float32},1}
false

I think the mechanism here is the same case as:

julia> Array{Int32,1} <: Array{Int,1}
false

even if Int32 is a special case of Int, julia will return a false here.

Bacause Array{Array{Float32,1},1} is just a special case of Array{Array{Float32,N},1} with N = 1

so this statement is not true because Array{Float32,1} and Array{Float32,N} are type parameters which are invariant in julia.

Upvotes: 5

Related Questions