I was just wondering on how one could do multiple dispatch when using a decorator pattern and subtypes.
Imagine the following example
abstract type A end
struct A1 <: A
c::Int
end
struct A2 <: A
c::Float64
end
struct decoA{B <: A} <: A
a::A
name::String
end
decoA(a::B, s) where {B <: A} = decoA{B}(a,s)
basically this leads to 4 possible types
a1 = A1(1)
a2 = A2(1.)
a3 = decoA(a1,"Hi.")
a4 = decoA(a2,"Moin.")
with method dispatch on the first two I would write something (don’t mind the logic, it’s merely to illustrate the dispatch question)
f(a::A1) = A1(a.c*2)
f(a::A2) = A2(a.c/2)
then you get
julia> f(a1)
A1(2)
julia> f(a2)
A2(0.5)
now to the question: I would like to implement f
also for the deco-cases, such that
f(a3)
is the same as decoA(f(a1),"Hi.")
and f(a4)
is the same as decoA(f(a2),"Moin.")
,
so to a certain extend, that f
and decoA
interact in a quite transparent way.
What’s the most elegant way to achieve such a dispatch with decorator pattern based types?
Edit: I actually found the answer to my MWE myself, it’s f(a::decoA{T}) where {T <: A) = decoA(f(a.a),a.name)
but that was merely due to my too simple MWE.
I would like to have an easy dispatch for all types A1, decoA{A1}, decoB{A1}
, where decoB
is similar to decoA
, i.e. also with one parameter type and still a subtype of A
, Can something like that be made with dispatch?