Reputation: 1328
I have a parametric type. For example:
> Array([1 2;3 4])
Its type is
> typeof(Array([1 2;3 4]))
Array{Int64,2}
I can get the first type parameter using eltype
:
> eltype(typeof(Array([1 2;3 4])))
Int64
How can I access second and possibly other type parameters?
Upvotes: 5
Views: 1182
Reputation: 20248
If you're speaking specifically of (Abstract)Array
types, then the dimension can be retrieved using ndims
:
julia> ndims(Array{Int64, 2})
2
If, on the other hand, you want to write a custom function that extracts a given parameter from a parametric type, you can use build one like this:
julia> second_param(::Type{Array{T, N}}) where {T, N} = N
second_param (generic function with 1 method)
julia> second_param(Array{Int64, 2})
2
(I'm using Array
here for the sake of the example, but the same kind of construct could be used to extract parameters from any other parametric type)
Upvotes: 6
Reputation: 69839
What François Févotte recommends is best and safest. However, if you wanted to dig into the internals (again - I would not recommend it in production code, but sometimes it is useful) then you can write:
get_parameters(x::DataType) = collect(x.parameters)
Now you can get a vector of parameters of x
for any type that is DataType
:
julia> get_parameters(Vector{Int})
2-element Array{Any,1}:
Int64
1
julia> get_parameters(Int)
0-element Array{Any,1}
julia> get_parameters(Dict{Int, Union{String, Missing}})
2-element Array{Any,1}:
Int64
Union{Missing, String}
The benefit here is that x
you pass can be any DataType
.
Upvotes: 3