How to access the parameter list of a super type


#1

Hi fellows,

Here is what i want to do:

abstract type DEF{super<:Tuple}


struct X <: DEF{Tuple{F,Y,Z{Int}}}

end

I want to access the supertype of X which is DEF
and specifically what types are in the tuple Tuple{F,Y,Z{Int}}}
F, Y and Z{Int} as types
How can i do that?

Thanks.


#2

when creating a method that does something with variables of type X you need to include a where clause in the method signature so that Julia knows how to branch off different types. Here is a minimally working example:

abstract type DEF{Super <: Tuple}
end #even abstract type definitions need an end

#note the type parameters for X, they tell the compiler that F, Y, and Z are typevars and not existing types
struct X{F,Y, Z} <: DEF{Tuple{F, Y, Z} }
end

function does_something(x::X{F,Y, Z}) where {F, Y, Z}
    println("F is an $F, Y is a $Y, Z is a $Z") #use F, Y, and Z like any normal type
    z = Z() # a variable of type Z, assuming it has an appropriate constructor
end

#3

The internal structure of type X is somewhat convoluted, but you can retrieve the individual type parameters as follows (Julia v0.6.2):

julia> X.var
F

julia> X.body.var
Y

julia> X.body.body.var
Z

#4

These are implementation details, and accessing them is not good style (they may change without warning or deprecation).

Within functions, the approach suggested by @Philip_Stuckey above is best, but if the parameter is needed explicitly, it can be extracted with a function like

gimme_Z(::X{F,Y,Z}) where {F,Y,Z} = Z

#5

There is a section in the manual:

https://docs.julialang.org/en/latest/manual/methods/#Design-Patterns-with-Parametric-Methods-1


#6

But i wouldn’t know how many elements there are in the tuple at time.

What else can i do?

Thanks


#7

Well, one could argue that you shouldn’t handle type parameters when you don’t know what they stand for. Translated to your problem: you should enumerate the different possibilities. Otherwise, does post 3 not work?


#8

I guess the simplest answer would be put a threshold and use that much elements in the tuple as max.

Thanks