As an artificial example suppose I have a parametric struct where T <: AbstractFloat
mutable struct Summary{T<:AbstractFloat}
count
sum::T
end
I would like to type the count
field as UInt16
when T === Float16
or as UInt32
when T === Float32
and as UInt64
in all other cases.
My current approach is to use a union type Union{UInt16, UInt32, UInt64}
for the count
field
module SummaryStats
export Summary, avg
const CounterType = Union{UInt16, UInt32, UInt64}
mutable struct Summary{T<:AbstractFloat}
count::CounterType
sum::T
# explicitly typed no-arg constructor
Summary{T}() where {T<:AbstractFloat} = new(_counter(T), zero(T))
end
# untyped no-arg constructor defaults to Float64
Summary() = Summary{Float64}()
function avg(summary::Summary{T})::T where {T <: AbstractFloat}
if summary.count > zero(_counter(typeof(T)))
summary.sum / summary.count
else
zero(T)
end
end
# internal helper functions, not exported
Base.@pure _counter(::Type{Float16})::UInt16 = UInt16(0)
Base.@pure _counter(::Type{Float32})::UInt32 = UInt32(0)
Base.@pure _counter(::DataType)::UInt64 = UInt64(0)
end # module
This seems to work but, obviously, @code_warntype
is not happy with the union type for the count
field.
I am wondering whether it is possible to somehow compute the correct concrete type according to the rules laid out above?