Skip to content

feature request: Compose trait for strings and functions #16541

Closed
@apoelstra

Description

@apoelstra

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 a compose function that sugars to the ++ operator.
  • Implement this on String for concatenation, and Fn traits for composition (edit this actually doesn't make sense for functions that aren't A->B and B->C, never mind). This replaces add for String.
  • 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions