A question about parametric types


#1

Hi
I have the following problem:

struct MyType{T}
end

function get_root_type(typ::Type)
#what goes here?
end

rt = get_root_type(MyType{Int})

i need rt to contain type MyType , without any parameter.

Is there a way to do this?
Thanks


#2

How about this?

struct MyType{T}
end

get_root_type{T}(::MyType{T}) = T

get_root_type(typ::Type) = get_root_type(eval(:($typ()))

Then

julia> rt = get_root_type(MyType{Int})
Int64

#3

This is not what i want, i don’t want the parameter, i want MyType
and MyType can be any type with parameters.
Thanks.


#4

Oh okay, this is one way of getting it using Regex

get_root_type(typ::Type) = match(r"[^({.+})]+",string(typ)).match |> Symbol |> eval

Then

julia> rt = get_root_type(MyType{Int})
MyType

#5
get_root_type(typ::Type) = typ.name.wrapper

#7

That will not change anything.

julia> struct MyType{T}
       end

julia> typeof(MyType)
UnionAll

julia> UnionAll <: Type
true

#8

What’s your intended application?


#9

In v0.7, there is nameof, eg

julia> struct MyType{T} end

julia> nameof(MyType{Int})
:MyType

In v0.6 I think it was Base.datatype_name.

This is gloriously horrible :wink:


#10

this is Julia, so if you don’t know an official way of doing things, you can usually at least easily create an inefficient way of doing something, until someone corrects it


#11

As a general rule, going to strings and back for reflection/metaprogramming is usually a sign that you are not using something provided by the language.


#12

Yes you are right, this calls for an application related solution which i generated the required functions via metaprogramming.

Thanks…


#13

Thanks.
This also works.


#14

This wouldn’t work if the type is in a different module such as MyModule.MyType
Thanks


#15

Try

function get_root_type(typ::Type)
    typ.name
end

Purists may object, but it gets the job done.