What does it mean for opCmp and opEquals to be consistent?

Steven Schveighoffer schveiguy at yahoo.com
Thu Apr 3 12:33:13 PDT 2014


On Thu, 03 Apr 2014 14:45:40 -0400, monarch_dodra <monarchdodra at gmail.com>  
wrote:

> On Thursday, 3 April 2014 at 16:47:05 UTC, Steven Schveighoffer wrote:
>> This can lead to false positives if opCmp(x, y) == 0 is assumed to mean  
>> equal.
>>
>> An example: if you used RBTree to store 2d points, and defined opCmp  
>> like you did, then you wouldn't be able to store both (1, 0) and (0, 1)  
>> in the same RBTree without duplicates.
>>
>
> RBTree make no claim to test for equality, but only equivalence, and I'd  
> find it perfectly normal for RBTree to not store both (0, 1) / (1, 0).

I think a user of your 2d point may object to both (0,1) and (1,0) not  
being stored.

>
> An AA, on the other hand, really shouldn't care about equivalence, only  
> equality.

This means, an AA which uses opCmp for collisions may get to a point where  
opCmp returns 0, then has to additionally call opEquals defensively. I  
don't think this is a good situation.

Note, I don't agree with using opCmp for collisions at all, but to say  
opCmp should be inconsistent with opEquals is not valid.

In your example, I would say a *property* of the point can have partial  
ordering, and in that case, opCmp is not the right fit. With D, it's all  
to easy to simply use a property for ordering, if that is what you wish.

But if I wanted to define opCmp on a 2d point, I would first compare x,  
then y.

-Steve


More information about the Digitalmars-d-learn mailing list