either

Justin Johansson noreply at jj.com
Tue Jan 11 01:10:28 PST 2011


On 10/01/11 05:42, Andrei Alexandrescu wrote:
> I wrote a simple helper, in spirit with some recent discussions:
>
> // either
> struct Either(Ts...)
> {
> Tuple!Ts data_;
> bool opEquals(E)(E e)
> {
> foreach (i, T; Ts)
> {
> if (data_[i] == e) return true;
> }
> return false;
> }
> }
>
> auto either(Ts...)(Ts args)
> {
> return Either!Ts(tuple(args));
> }
>
> unittest
> {
> assert(1 == either(1, 2, 3));
> assert(4 != either(1, 2, 3));
> assert("abac" != either("aasd", "s"));
> assert("abac" == either("aasd", "abac", "s"));
> }
>
> Turns out this is very useful in a variety of algorithms. I just don't
> know where in std this helper belongs! Any ideas?

Despite that it may be very useful as you say, personally I think it is 
a fundamental no-no to overload the meaning of "==" in any manner that 
does not preserve the generally accepted semantics of equality which 
include the notions of reflexivity, symmetry and transitivity**.

**See http://en.wikipedia.org/wiki/Equality_%28mathematics%29

The symmetric and transitive properties of the equality relation imply 
that if (a == c) is true and if (b == c) is true then (a == b) is also true.

In this case the semantics of the overloaded "==" operator have the 
expressions 1 == either(1, 2, 3) and 2 == either(1, 2, 3) both 
evaluating to true and by implication/expectation (1 == 2).

Clearly though, (1 == 2) evaluates to false in terms of the commonly 
accepted meaning of equality.

Just my 2 cents and I wonder if there some other way of achieving the 
desired functionality of your helper without resorting to overloading 
"==" and the consequential violation of the commonly held semantics of
equality.

Cheers,
Justin Johansson


More information about the Digitalmars-d mailing list