ProtoObject and comparison for equality and ordering

Adam D. Ruppe destructionator at gmail.com
Tue May 14 21:29:10 UTC 2019


On Tuesday, 14 May 2019 at 20:36:08 UTC, Eduard Staniloiu wrote:
> Adding some more context to this

thanks, yeah I missed most of dconf for various reasons 
(hopefully will catch up when the videos released though) so this 
is good to read.

> Jonathan's question got us to the point raised: maybe it 
> doesn't make much sense to be able to compare two 
> `ProtoObjects`, so maybe you shouldn't be able to. This would 
> change the interface to

Yeah, I would agree with that. It is hard to imagine a class that 
should actually be ordered with respect to a totally separate and 
unknown class. How would you possibly compare `MyDomElement < 
MySimpleWindow`? It's absurd.

Let's try to think of a case where it might make sense. Maybe I 
define class MyString. That can be sorted along side with other 
MyStrings. Ditto with char[].

class MyString : Ordered!MyString, Ordered!(char[])

So what if you defined YourString that is basically the same. I 
can see the argument where maybe someone, using our two libraries 
together, would want to:

ProtoObject[] objs;
objs ~= new MyString();
objs ~= new YourString();
sort(objs);

But how would you even implement that now? You have to cast 
inside opCmp... and that means one of the two classes must know 
about the other to realize that cast.

And if they knew about the other, they could explicitly declare 
that in the interface list.

And then you would store `Ordered!YourString[] objs;` instead of 
`ProtoObject`; make an array of the least common ancestor that 
actually defines the necessary interface.

So...

> ```
> interface Ordered(T)
> {
>     int opCmp(scope const T rhs);
> }
> ```

Yeah, I don't think we actually lose anything of value going this 
way. Let's do it.


> Since we are here, I want to raise another question:
> Should `opCmp` return a float?

My view is if they cannot be compared, they shouldn't implement 
the interface.

For cases where some values are comparable and some aren't (like 
float.nan or maybe null), I'm kinda ok just saying you return -1 
or whatever and it is undefined order.


More information about the Digitalmars-d mailing list