Stream: helpdesk (published)

Topic: Functions of abstract parametric types


view this post on Zulip Mike (Jun 16 2021 at 18:05):

Suppose I have an abstract parametric type with two subtypes:

abstract type A{T} end
struct B{T} <: A{T} end
struct C{T} <: A{T} end

I want to write a general function that takes either of these types with some T, and returns the same type — but with a different parameter. I'm having a hard time searching for this because I don't even know what words to use for this concept.

Obviously, I could code these up explicitly:

f(a::B{T}) where T = B{Float64}()
f(a::C{T}) where T = C{Float64}()

But we're all much too sensible and lazy for that. I know that I could loop over [:B, :C] and @eval these methods into existence, but that's getting complicated quickly. Is there some simpler and/or more elegant method?

view this post on Zulip Andrey Oskin (Jun 16 2021 at 18:20):

From this very old discussion https://discourse.julialang.org/t/extract-type-name-only-from-parametric-type/14188/20

f(a::T) where {T <: A} = Base.typename(T).wrapper{Float64}()

julia> x = B{Int}()
B{Int64}()

julia> f(x)
B{Float64}()

julia> x = C{Int}()
C{Int64}()

julia> f(x)
C{Float64}()

view this post on Zulip Andrey Oskin (Jun 16 2021 at 18:20):

It's somewhat scary of course, but still valid.
Probably there are better ways already.

view this post on Zulip Mike (Jun 16 2021 at 18:55):

This looks like a good solution. Should also work when somebody else comes along and creates another subtype; my loop over [:B, :C] wouldn't work for those types. Thanks!

view this post on Zulip Mason Protter (Jun 16 2021 at 19:00):

Yeah, this is something that for whatever reason, the julia devs seem to thing is not important enough to be an actual language feature and I don't understand why

view this post on Zulip Jakob Nybo Nissen (Jun 17 2021 at 10:17):

I think the recent comments in https://github.com/JuliaLang/julia/issues/35543 suggest it will be made a language feature soon-ish


Last updated: Oct 02 2023 at 04:34 UTC