8

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?

2

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

5

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.