A fresh look at comparisons

Yigal Chripun yigal100 at gmail.com
Wed Apr 16 10:54:25 PDT 2008


Janice Caron wrote:
> On 16/04/2008, Yigal Chripun <yigal100 at gmail.com> wrote:
>   
>>  I don't think D should limit opCmp to be non virtual. That
>>  should be decided by the programmer (if needed the programmer can use
>>  "final").
>>     
>
> It would be a very bad thing indeed for anyone to make opCmp()
> non-virtual, aka final.
>
> I have suggested something completely different. I have suggested that
> if comparison is defined for class A, but not for class B which is a
> subclass of A, then by default, objects of type B shall be considered
> incomparable.
>
> That is absolutely /not/ the same thing as implementing final opCmp()
> in A. All final would do is block polymorphism (which would be worse,
> actually, since that would actually /prevent/ B's opCmp() from being
> used in some situations). It wouldn't stop b < c from calling
> A.opCmp().
>
> final stops derived class functions from being called, which is the
> wrong direction. I propose the opposite - that base class functions
> not be called. There is currently no mechanism in D which allows one
> to specify that.
>   

Someone on this thread made a very good observation: opCmp should be a
multi-method.
This is an excellent idea and applies to more than just opCmp.

given the following classes:
class A {}
class B : A {}
class C : A {}

I'd suggest the following syntax for multi-methods: (taken from the
article linked bellow)
void func(virtual  A a1, virtual  A a2);
so both a1 and a2 can also be of any subtype of A.

let's look at some of the comparison variations:
opCmp(A a1, A a2); // compare only instances of A
opCmp(virtual A a1, virtual A a2); // will work on all subtypes
opCmp(virtual B b1, virtual B b2); // this overrides the above more
general function
etc...
I think this can provide all possible combinations needed.

So basically I think a general multi-method implementation should be
added to D instead of special treatment for opCmp.
opCmp should be implemented as a free-function and not as a method. I
still think there should be a comparable interface to tag types that can
be compared. in general tagging classes with empty interfaces (like in
Java) is a good idiom. for example, D AAs can be defined to contain any
type that implements comparable. [a future direction: implementing
attributes/annotations and use those instead]

It's also worth considering making all binary operators free functions
instead of methods, and for commutative ops the compiler can run both
op(a, b) and op(b,a). I'm not sure about this one, though, and would
like to hear what others think about the pros and cons of that approach...

an article about how to cleanly add multiple dispatch to C++ by Bjarne
Stroustrup, Yuriy Solodkyy and Peter Pirkelbauer:
http://research.att.com/~bs/multimethods.pdf

-- Yigal



More information about the Digitalmars-d mailing list