I have been thinking about parametric types lately and how to use them so I came up with a thought experiment that I can’t seem to figure out, but I am pretty sure is possible. For this experiment lets assume there is a boolean associated with a type. There are two method routes for this type one to be taken one if the boolean is true, and one to be taken if it is false.
I could see this as an alternative to a situation where you have a base type and then two subtypes one that signals a condition is true and one that signals an alternate condition. And where the only difference between the subtypes is the presence or absence of this condition. In essence I want to implement this functionality only by storing the boolean as a parametric and not a field. This code shows the non-parametric way of doing this:
struct WorkingType{T}
B::Bool
s::T
end
w = WorkingType(true, 10) # true condition
w2 = WorkingType(false, 10) # false condition
testval(w) = w.B ? print(w.s) : print(-1 * w.s)
testval(w) # 10
testval(w2) # -10
Now lets assume i still want to store s in a field but have its type as a parametric so it can support a variety of types and I just want Julia to dispatch to the correct function based on the (Boolean) parametric being true or false. Here is an outline of what I think needs to happen with ??? where I am unsure of the syntax.
struct BustedType{B, T}
s::T
end
t = BustedType{???}(???) # true condition
t2 = BustedType{???}(???) # false condition
testval(::BustedType{???}) = print(???) # 10
testval(::BustedType{???}) = print(-1 * ???) # -10
Bonus question: Would it be possible to do the above except store both S and B as parametric values and then switch on three conditions ex:
- s < 10 && b is true = print 1
- s >= 10 && b is true = print 1 * s
- s is false = print -1 * s