Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the specific type from an instance of a generic type in julia?

How do I get the subtype of an instance of an parametric type in julia? For example:

immutable Dog{T <: Number}
    snout::T
end

dog = Dog(5.)
typeof(dog)

...returns Dog{Float64}. Is there a way to get at the type Float64 from the variable dog without referring explicitly to the field snout?

like image 538
user3271788 Avatar asked Jul 14 '15 20:07

user3271788


People also ask

What is mutable struct in Julia?

type and immutable are valid up to julia 0.6, mutable struct and struct are the names of the same objects in julia 0.6 and forward. mutable in mutable struct means that the fields can change - which is actually fairly rarely used so being immutable is the default. mutable struct 's are slower than struct s.


2 Answers

It depends on your use case. If you are interested in a specific case like this, a good way is to define a function

dogtype{T}(::Dog{T}) = T

Then dogtype(Dog(.5)) will give you Float 64.

This is the kind of pattern that is used to implement the eltype function in base Julia.

like image 89
Toivo Henningsson Avatar answered Nov 15 '22 07:11

Toivo Henningsson


This works for me:

julia> VERSION
v"0.4.0-dev+5733"

julia> immutable Dog{T <: Number}
           snout::T
       end

julia> dog = Dog(0.5)
Dog{Float64}(0.5)

julia> typeof(dog).parameters[1]
Float64
like image 36
Tom Breloff Avatar answered Nov 15 '22 06:11

Tom Breloff