Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a Vector to have all elements to be of the same type in Julia?

Tags:

julia

I need to define a Vector such that all elements in it need to be of the same type, though the type itself can be of any type. I tried the below:

["1", 2] isa AbstractVector{T} where T <: Any

but this returns true.

The following works in this case and correctly returns false as needed:

["1", 2] isa AbstractVector{T} where T <: Union{AbstractString, Number}

But, I don't want to restrict the type to be only Strings, Numbers etc. So, how else can I restrict all elements of a Vector to be of the same type though the type itself can be flexible?

like image 558
WebDev Avatar asked Nov 07 '22 17:11

WebDev


1 Answers

["2", 2] is of type Vector{Any} and T <: Any is true because setting T = Any gives Any <: Any which should evaluate to true.

"1" is a String and String <: AbstractString is true. But Julia's type system only works like this

T{S} <: T'{S} is true if T <: T' but is not true if T{S} <: T{S'} even if S <: S'. I don't know the technical term for that in type theory but it should be detailed in here https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)

like image 98
xiaodai Avatar answered Nov 15 '22 06:11

xiaodai