A fresh look at comparisons

Henning Hasemann hhasemann at web.de
Mon Apr 14 02:20:40 PDT 2008


I like this proposal but it might have efficiency issues when you need
to find out quickly if you want to order two values (you would often
have to call both functions).

What about this (much more primitive) approach:

class C {
	int category;
	int x;

	ComparsionResult opCompare(C other) {
		if(category == other.category) {
			// This could be shortened to something like
			// int.compare(x, other.x)
			if(x == other.x) {
				return ComparsionResult.EQUAL;
			}
			else if(x > other.x) {
				return ComparsionResult.GREATER;
			}
			else {
				// a < b is "unkown" meaning
				// compiler will try to get it via
				// b > a which is defined above
				return ComparsionResult.UNKNOWN;
			}
		}
		else {
			// Objects are simply incomparable
			// (like (1 - i) and (i - 1) for example)
			return ComparsionResult.UNDEFINED;
		}
	} // opCompare()
} // class C

whereas ComparsionResult would be an enum defined in object.d or so.
This should avoid all mentioned issues without a syntax change.

Henning
			

-- 
GPG Public Key:
http://gpg-keyserver.de/pks/lookup?op=get&search=0xDDD6D36D41911851




More information about the Digitalmars-d mailing list