Boost logo

Boost :

Subject: Re: [boost] Boost.Algorithm design question
From: Andrew Sutton (asutton.list_at_[hidden])
Date: 2011-10-06 18:51:55

> bool operator== ( orange const& l, apple const& r )
>    { return l.weight == r.weight; } // comparing apples with oranges?!

The expression "like comparing apples and oranges" is not usually
meant to inspire confidence in the act of comparison. Just because
it's legal doesn't make it good.

A definition of equality should support equational reasoning. If two
values are equal, then you should be able to substitute one for the
other and produce an equivalent program. I seriously doubt that
substituting an apple in place of an orange would produce an
equivalent program; it will probably result in type errors. Objects of
different types cannot be equal (with some exceptions).

Even if apples and oranges were structurally identical, your operator
does not define equality. What about color? Could I substitute an
orange of equal weight in the following program to produce a correct

apple x = pick_fruit(tree);
assert(x.color != orange);

I suspect not. Your apples and may equivalent weights, but they are
not equal. Equivalence is more general than equality and is not
sufficient to guarantee substitutability.

I suppose it doesn't really matter if you're just trying to make your
program look neat, but if you have to formally verify your system,
you'd better nail down the semantics. As far as I know there are no
systems of logic that have, in their basis, equality defined for
objects of different types.

The correct way to write the comparison is:

  weight(a) == weight(o)

Assuming that weights are numeric, I'm reasonably certain that there's
an operator that conforms to the ideal. Even if the results of these
operations are typed quantities (1kg vs 1/4lb), there's a principle
that allows correct and semantically meaningful comparison: both can
be converted to a common type and compared.

Comparing apples and oranges remains as meaningless an operation as
the idiom suggests.

Boost list run by bdawes at, gregod at, cpdaniel at, john at