I would like to do the following
function foo(a::T{R1}, b::T{R2}) where {R1,R2, T <: SomeAbstractType}
end
but this doesn't compile.
Is there a way to accomplish such a thing? I want foo
to dispatch only when a,b
have the same subtype of some abstract type but possibly different type parameters.
edit: missing curly bracket, clarification
Is your abstract type also parametrized? If so, I think you could do
function foo(a::T, b::T) where {R1,R2, T <: SomeAbstractType{R1,R2}}
end
It is, but only with one type parameter, so that does not work.
This must be possible, I think, since one can do:
julia> f(xx::Vector{Int}, yy::Vector{Float64}) = true
f (generic function with 2 methods)
julia> f([1, 2], [1.0, 2.0])
true
function foo(a::T1, b::T2) where {R1,R2, T1 <: SomeAbstractType{R1}, T2 <:SomeAbstractType{R2}}
end
but probably there's a more elegant version
Max Köhler said:
function foo(a::T1, b::T2) where {R1,R2, T1 <: SomeAbstractType{R1}, T2 <:SomeAbstractType{R2}} end
but probably there's a more elegant version
Thanks, but this doesn't satisfy the question since it dispatches even if T1 and T2 are different subtypes of SomeAbstractType.
e.g.
julia> abstract type Bar{T} end
julia> struct Bar1{T} <: Bar{T} end
julia> struct Bar2{T} <: Bar{T} end
julia> function foo(a::T1, b::T2) where {R1, R2, T1<:Bar{R1}, T2<:Bar{R2}}
return true
end
foo (generic function with 1 method)
julia> b = Bar1{Int}()
Bar1{Int64}()
julia> a = Bar2{Float64}()
Bar2{Float64}()
julia> foo(a,b)
true
but can't you just do
function foo(a::T1, b::T2) where {R1,R2, T1 <: Bar1{R1}, T2 <:Bar1{R2}}
end
then?
and
function foo(a::T1, b::T2) where {R1,R2, T1 <: Bar2{R1}, T2 <:Bar2{R2}}
end
respectively
Yeah. This works for my actual problem, but then I would need to define one of these for each subtype of Bar. It's more academic at this point but I'm wondering if this can work for arbitrary subtypes of Bar.
ye sorry if my answer is not satisfying, but I actually think it's a nice problem, so happy to hear other solutions as well
Max Köhler said:
ye sorry if my answer is not satisfying, but I actually think it's a nice problem, so happy to hear other solutions as well
no problem, I appreciate the answers!
I think for a general approach, this conversation is essentially the same problem, isn't it? https://julialang.zulipchat.com/#narrow/stream/274208-helpdesk-.28published.29/topic/Functions.20of.20abstract.20parametric.20types
Last updated: Nov 06 2024 at 04:40 UTC