# \`x - y\` is not \`x + (-y)\`?

**URL:** <https://discourse.julialang.org/t/x-y-is-not-x-y/39726>\
**Category:** General Usage\
**Tags:** type\
**Created:** [May 18, 2020, 11:45pm UTC](https://discourse.julialang.org/t/x-y-is-not-x-y/39726 "2020-05-18T23:45:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![heliosdrm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/heliosdrm/32/3851_2.png) [@heliosdrm](https://discourse.julialang.org/u/heliosdrm)\
**Post date:** [May 18, 2020, 11:45pm UTC](https://discourse.julialang.org/t/x-y-is-not-x-y/39726/1 "2020-05-18T23:45:45Z")

</div>

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)](https://books.google.es/books?id=URK2DwAAQBAJ&pg=PA51&lpg=PA51)

However this is not a rule for Julia types:

```julia
struct CustomNumber{T}
    data::T
end

Base.:+(x::CustomNumber, y::CustomNumber) = CustomNumber(x.data + y.data)
Base.:-(x::CustomNumber) = CustomNumber(-x.data)

```

```julia-repl
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:

```julia
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`.

---

<div class="post-metadata">

**Author:** ![jlapeyre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlapeyre/32/4514_2.png) [@jlapeyre](https://discourse.julialang.org/u/jlapeyre)\
**Post date:** [May 19, 2020, 12:57am UTC](https://discourse.julialang.org/t/x-y-is-not-x-y/39726/2 "2020-05-19T00:57:33Z")

</div>

That’s a good question. One might audit how often binary subtraction is defined using unary minus in existing code. If it’s used a lot, then it might be a good idea to make it a fallback. But, if it is not used much now, then it would be better to leave it undefined. People might forget to implement an efficient method if the fallback “just works” without thinking about it.

Similar issues arise in LinearAlgebra.

---

<div class="post-metadata">

**Author:** ![heliosdrm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/heliosdrm/32/3851_2.png) [@heliosdrm](https://discourse.julialang.org/u/heliosdrm)\
**Post date:** [May 19, 2020, 7:29am UTC](https://discourse.julialang.org/t/x-y-is-not-x-y/39726/3 "2020-05-19T07:29:18Z")

</div>

Good point. I see: `Base.:-(x, y) = x + (-y)` needs to allocate the intermediate result of `-y`, so usually it may be better to write an explicit subtraction method. Such a fallback might come in handy for complicated types, but in such a case the penalty of allocating `-y` would probably be greater, so the previous argument would be stronger.
