merch
merch

Reputation: 945

Julia: write a union of types using "abstract type"

I am trying to write the following union of types:

FloatVector = Union{Array{Float64,1}, DataArray{Float64,1}, Array{Union{Float64, Missings.Missing},1}};

using the abstract types syntax. Ideally, I would like to do something similar to this link. I tried the below, but unfortunately it does not work:

abstract type FloatVector end
type Array{Float64,1} <: FloatVector end
type DataArray{Float64,1} <: FloatVector end
type Array{Union{Float64, Missings.Missing},1} <: FloatVector end

I am not confident with abstract types and I couldn't find a good reference on a similar problem. I would be glad if you could explain me how to proceed and the advantages over the Union.

Upvotes: 2

Views: 644

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69939

It is not possible to do what you want using abstract types in Julia. Union is a way to represent your requirement.

Now to understand why observe that in Julia type system you have three restrictions:

  1. Only abstract types can have subtypes.
  2. A type can have only one supertype.
  3. You have to specify a supertype of a type when defining it.

In this way we know that types create a tree like structure, where the root is Any (with the exception of Union{} which has no values and is subtype of all other types, but you will probably not need this in practice).

Your definition would violate rule #2 and rule #3. Observe that all those types are already defined (either in Base or in a package) - so you cannot redefine them (rule #3). Also they already have a supertype so you cannot add another (rule #2). See for example the result of this call:

julia> supertype(Array{Float64, 1})
DenseArray{Float64,1}

And you see that Array{Float64, 1} is already defined and has a supertype.

Having said that maybe another more general definition will be just enough for you:

const FloatOrMissingVector = AbstractVector{<:Union{Float64, Missing}}

This definition has two differences:

  1. It allows other than dense vectors (which I guess is what you would want anyway as typically you do not care if a vector is dense or sparse)
  2. It would allow e.g. Vector{Missing} as a subtype (so a structure containing only missing values) - if you would want to rule this out you would have to specify union as you have proposed above.

Upvotes: 4

Related Questions