ProtoObject and comparison for equality and ordering

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Wed May 15 00:32:32 UTC 2019


On 5/14/19 1:23 AM, Mike Franklin wrote:
> On Wednesday, 15 May 2019 at 00:08:10 UTC, Andrei Alexandrescu wrote:
> 
>> This won't work because the result of opCmp is compared against zero. 
>> Using a floating point number is likely to be more efficient.
> 
> Please consider the fact that some microcontrollers don't have an FPU.  
> Some may have a software floating point implementation but consider the 
> cost in flash memory consumption and performance implementing such a 
> thing in software.  It seems excessive.

Writing D code assuming float comparison is prohibitively expensive 
seems an .

> Although it would be much more work, perhaps what is needed is a new 
> type (e.g. `struct CmpResult`) with 4 immutable instances representing 
> each result and an `opCmp` and `opEquals` implementation that does the 
> right thing comparing against 0 or whatever else is needed.  Yes, it's 
> more complicated, but I think it would scale better.

Not sure there's much to gain there. a < b is lowered to a.opCmp(b) < 0. 
So then... you define opCmp to return an instance of this:

---
import std.stdio;

struct OverengineeredCmpResult {
     enum R { lt, eq, gt, ionno }
     private R payload;
     int opCmp(int alwaysZero) {
         writeln("b");
         return 0;
     }
}

struct A {
     OverengineeredCmpResult opCmp(A rhs) {
         writeln("a");
         return OverengineeredCmpResult(OverengineeredCmpResult.R.ionno);
     }
}

void main() {
     A a, b;
     if (a < b) {}
}
---

Much ado about nothing.


More information about the Digitalmars-d mailing list