Hi,
I have defined the following types:
struct Percentage <: Real
value::Float64
Percentage(x) = x < 0 ? new(0) : x > 1 ? new(1) : new(round(x, digits = 6))
end
Base.show(io::IO, x::Percentage) = print(io, "$(x.value * 100)%")
Base.convert(::Type{Percentage}, x::Real) = Percentage(x)
Base.convert(::Type{Percentage}, x::Percentage) = x
Base.promote_rule(::Type{T}, ::Type{Percentage}) where T <: Real = Percentage
import Base: +, -, *, /, <, >, <=, >=, ==
+(x::Percentage, y::Percentage) = Percentage(x.value + y.value)
-(x::Percentage) = Percentage(-x.value)
-(x::Percentage, y::Percentage) = Percentage(x.value - y.value)
*(x::Percentage, y::Real) = Percentage(x.value * y)
/(x::Percentage, y::Real) = Percentage(x.value / y)
<(x::Percentage, y::Percentage) = x.value < y.value
<=(x::Percentage, y::Percentage) = x.value <= y.value
>(x::Percentage, y::Percentage) = x.value > y.value
>=(x::Percentage, y::Percentage) = x.value >= y.value
==(x::Percentage, y::Percentage) = x.value == y.value
Base.max(x::Percentage, y::Percentage) = Percentage(max(x.value, y.value))
Base.min(x::Percentage, y::Percentage) = Percentage(min(x.value, y.value))
mutable struct Health <: Real
current::Percentage
Health(current=1) = new(current)
end
Base.convert(::Type{Health}, x::Real) = Health(x)
Base.convert(::Type{Health}, x::Health) = x
Base.promote_rule(::Type{T}, ::Type{Health}) where T <: Real = Health
Base.promote_rule(::Type{Health}, ::Type{Percentage}) = Health
import Base: +, -, *, /, <, >, <=, >=, ==
+(x::Health, y::Health) = Health(x.current + y.current)
-(x::Health) = Health(-x.current)
-(x::Health, y::Health) = Health(x.current - y.current)
*(x::Health, y::Real) = Health(x.current * y)
/(x::Health, y::Real) = Health(x.current / y)
<(x::Health, y::Health) = x.current < y.current
<=(x::Health, y::Health) = x.current <= y.current
>(x::Health, y::Health) = x.current > y.current
>=(x::Health, y::Health) = x.current >= y.current
==(x::Health, y::Health) = x.current == y.current
Base.max(x::Health, y::Health) = Health(max(x.current, y.current))
Base.min(x::Health, y::Health) = Health(min(x.current, y.current))
When I run the following code
h = Health(0.3)
h.current += Health(0.1)
I get the following error:
ERROR: MethodError: no method matching decompose(::Health)
I’m guessing it has to do something with the promote rules. Is there a way to fix this? I’m not using that line of code literally; in the real code it looks like:
h.current += x
where x has been assigned a value of type Health.
Thanks in advance,
Stef