Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parameters of a parametric type

Tags:

types

julia

Suppose I define a type like that

type Point{Tx, Ty} end

Then I create a variable of this type, for example,

a = Point{Int64, :something}()

Now, I only know that I can get the type of a by typeof(a). That is, Point{Int64, :something}. But, what I need is just the parameters Tx and Ty.

Are there ways that I can get those parameters Tx and Ty?

like image 765
Po C. Avatar asked Mar 02 '16 22:03

Po C.


2 Answers

You can define a function as follows

eltypes{Tx,Ty}(::Type{Point{Tx, Ty}}) = (Tx, Ty)
eltypes(p) = eltypes(typeof(p))

(here ::Type{Point{Tx, Ty}} matches an argument of type Point{Tx, Ty}) and use it

julia> eltypes(Point{Int, Float64}())
(Int64,Float64)

This is a frequently used idiom, for example in Base there is the similar function

eltype{T}(::Type{Set{T}}) = T
eltype(x) = eltype(typeof(x))
like image 147
mschauer Avatar answered Oct 12 '22 21:10

mschauer


typeof(a) is a DataType which has many fields. you can get those names via:

julia> fieldnames(DataType)
10-element Array{Symbol,1}:
 :name        
 :super       
 :parameters  
 :types       
 :instance    
 :size        
 :abstract    
 :mutable     
 :pointerfree 
 :ninitialized

so if you need those parameters, run

julia> collect(typeof(a).parameters)
2-element Array{Any,1}:
 Int64     
 :something
like image 21
Gnimuc Avatar answered Oct 12 '22 21:10

Gnimuc