Description
As @huonw mentions in #14482, mathematical convention is that addition is commutative. The stdlib already follows mathematical convention in some cases (for example, Zero
requires Add
and is expected to be the additive identity; ditto for One
and Mul
).
Currently everything in the stdlib which implements Add
implements add
as a commutative operator, except for strings. Therefore I propose:
- Introduce a
Compose
trait with acompose
function that sugars to the++
operator. - Implement this on
String
for concatenation, andFn
traits for composition (edit this actually doesn't make sense for functions that aren'tA->B
andB->C
, never mind). This replacesadd
forString
. - Add "must be commutative" to the documentation for
Add
.
This will help in writing generic code, since it is an (often unstated) assumption in many algorithms that+
is a commutative operator. It'll also make analysis easier since programmers won't have to memorize that+
means something different in rust than it does everywhere else.
It might also be worthwhile to add an empty()
constructor to Compose
to make it a monoid trait. Though as reem points out on IRC, Compose+Default
is probably preferable as it is more explicit.
Edit: Perhaps this should be on discourse, but it's a very minor (though breaking) change that cleans up the API and doesn't remove any functionality, and doesn't have any room for bikeshedding that I see. Sorry if I'm wrong on this point.