Fixing opEquals and opCmp

Nicholas Wilson via Digitalmars-d digitalmars-d at puremagic.com
Sat May 13 05:53:33 PDT 2017


On Saturday, 13 May 2017 at 12:11:49 UTC, Fool wrote:
> Is there any interest in fixing opEquals and opCmp in the 
> spirit(*) of [1]?
>
> Translating the basic idea into the D world would mean:
>  - Drop opEquals
>  - Encode the type of comparison in the return type of opCmp
>  - Adapt lowering
>
> Why?
>  - Simplicity: there is always only one function that needs to 
> be implemented;
>  - Consistency: implementation at a single place makes it more 
> difficult to get it wrong;
>  - Expressivity: through the return type implementors can 
> unambiguously specify the properties of comparison relations 
> (Equivalence, Equality, PartialOrdering, LinearOrdering, etc.) 
> and algorithms can more precisely specify their requirements 
> (e.g. general sorting requires a weak ordering whereas 
> topological sorting requires a preorder, only);
>
> [1] Herb Sutter: Consistent comparison, P0515 R0, 2017-02-05
>     URL 
> http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0515r0.pdf
>
> (*) Some aspects of the proposal are unsound but those can be 
> easily fixed.

For most types equality exists (i.e. are all members equal?), but 
ordering is nonsensical.

to answer your why questions:
1) see above, we're still doing better than C++ (although in the 
contexts of DLSs individual operator overloading is useful.
2) see 1. you need only define both if opEquals is a requirement 
for performance. defining opCmp suffices for (in)equality. and 
you don't define opCmp unless your type has sensible ordering.
3) you can do that already. w.r.t sort you pass a predicate 
(defaulting to "less") for which ordering is assumed to exist, if 
it doesn't then you get a partition according to that predicate.


More information about the Digitalmars-d mailing list