How to get array type parameters

Viewed 61

In Julia, if I make x = rand(10,2), then

>> typeof(x)
Matrix{Float64} (alias for Array{Float64, 2})

How do I access the type parameters, i.e., how do I obtain that the array x is an array of Float64 and 2?

1 Answers

(BTW: You are not looking for a 'subtype', as your title says, but for 'type parameters'.)

The element type is easy to get with eltype:

jl> eltype(x)
Float64

The dimensionality can be retrieved from the size of the array:

jl> length(size(x))
2

Edit: Better to use ndims:

jl> ndims(x)
    2

If you don't have access to x itself, but only its type, eltype still works:

jl> T = typeof(x);

jl> eltype(T)
Float64

The dimensionality is a bit more difficult. You can inspect the properties of the type variable (but I don't recommend that, since this is an internal implementation detail of the type, and may not be stable):

jl> T.parameters
svec(Float64, 2)

jl> T.parameters[2]

A better way is probably to make a function to get this for you:

jl> dims(::Type{<:AbstractArray{T, N}}) where {T, N} = N
dims (generic function with 3 methods)

jl> dims(T)
2

Edit: You can use ndims with type variables too:

jl> ndims(T)
2

So, actually, the answer is: eltype for the element type, and ndims for the dimensionality, both when you have an array and when you have the type of an array.

Related