In some places I have found that in computer algebra, x - y
can be defined as x + (-y)
. E.g. in Cohen’s Computer Algebra and Symbolic Computation: Mathematical Methods (page 51)
However this is not a rule for Julia types:
struct CustomNumber{T}
data::T
end
Base.:+(x::CustomNumber, y::CustomNumber) = CustomNumber(x.data + y.data)
Base.:-(x::CustomNumber) = CustomNumber(-x.data)
julia> CustomNumber(1) - CustomNumber(2)
ERROR: MethodError: no method matching -(::CustomNumber{Int64}, ::CustomNumber{Int64})
Of course, I can define the subtraction myself using that definition:
Base.:-(x::CustomNumber, y::CustomNumber) = x + (-y)
My question is whether there is some reason for not making that the fallback subtraction method in Base
.