Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia dispatch on parametric abstract type

Tags:

types

julia

Considering the following setup

abstract AbstractShape
type Shape_1 <: AbstractShape end
type Shape_2 <: AbstractShape end
type Shape_3 <: AbstractShape end

abstract AbstractElement{S<:AbstractShape}
type Element_1{S} <: AbstractElement{S} end
type Element_2{S} <: AbstractElement{S} end
#...
type Element_n{S} <: AbstractElement{S} end

I would like to retrieve the shape type parameter S of each concrete element type, e.g.

shape(::Type{Element_1{Shape_3}}) = Shape_3

using something like

shape{S}(::Type{AbstractElement{S}}) = S

so I don't have to write a shape function for each element type.

Is this possible and how would I do that? (Thanks for your help!)

like image 646
akun73 Avatar asked Dec 07 '25 08:12

akun73


1 Answers

I would not advise Gnimuc's workaround in 0.5, as it would fail if the concrete Element_ns did not all have the same kind; i.e. if perhaps Element_4{N,S} <: AbstractElement{S}.

Instead a better workaround is the trick used by eltype in 0.5; that is

shape{S<:AbstractShape}(::Type{AbstractElement{S}}) = S
shape{T<:AbstractElement}(::Type{T}) = shape(supertype(T))

On 0.6, of course, you may simply write the dispatch:

(shape(::Type{T}) where T <: AbstractElement{S} where S <: AbstractShape) = S
like image 122
Fengyang Wang Avatar answered Dec 09 '25 17:12

Fengyang Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!