WAT: opCmp and opEquals woes

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 23 12:04:37 PDT 2014


On Wed, Jul 23, 2014 at 11:49:58AM -0700, Andrei Alexandrescu via Digitalmars-d wrote:
> On 7/23/14, 11:09 AM, Dicebot wrote:
> >On Wednesday, 23 July 2014 at 17:15:12 UTC, Ary Borenszweig wrote:
> >>Imagine you have a list of integers and strings denoting integers:
> >>[1, "2", 100, "38"]. Now you want to sort them according to their
> >>numeric value. Of course, 1 and "1" would have the same order.
> >>However, 1 and "1" are different, so "==" would give false, while
> >>1.opCmp("1") would give 0.
> >>
> >>Equality and comparison are different. opCmp is used for sorting
> >>objects, which has nothing to do with equality. Inferring equality
> >>from opCmp is wrong in my opinion.
> >
> >Well this is why you can actually override those :) I think automatic
> >opCmd -> opEqual generation covers vast majority of use cases and as
> >such will have a vary good effort / decreased annoyance ratio.
> 
> I'd say let's leave things as they are. opEquals may need to do less
> work than opCmp, and it often sees intensive use. -- Andrei

If autogenerating opEquals to be opCmp()==0 is a no-go, then I'd much
rather say it should be a compile error if the user defines opCmp but
not opEquals. Currently, we have the bad situation where == behaves
inconsistently w.r.t. <, <=, >=, > because we allow opCmp to be defined
but opEquals not, and the default compiler implementation of opEquals
may or may not match the meaning of opCmp.

In short, what I'd like to see, in order of preference, is:

(1) If opCmp is defined but opEquals not, then opEquals should be
defined to be opCmp()==0.

(2) If (1) is a no-go, then the next best situation is that if opCmp is
defined but opEquals isn't, then the compiler should issue an error,
rather than implicitly generating a default opEquals that probably does
not match the programmer's expectations.

(3) If (2) is also a no-go, the 3rd best situation is that if opCmp is
defined but opEquals isn't, then the compiler should issue an error if
the user ever writes "a==b". That is, we allow the user to not define
opEquals as long as it's not actually used, but it's an error if it is
used.

(4) Do nothing, and allow the current hidden breakage to perpetuate and
make people hate D when they suddenly discover it when they forget to
implement opEquals.

I really hope we don't have to resort to (4).


T

-- 
All men are mortal. Socrates is mortal. Therefore all men are Socrates.


More information about the Digitalmars-d mailing list