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?

I feel like I should be able to do something like

f(a::D{T}) where {T, D<:A} = D{Float64}()

But all my attempts are being rejected.

view this post on Zulip Kwaku 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 Kwaku 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: Nov 22 2024 at 04:41 UTC