What is mathematically unsound about a >= b < c chained comparison?

249 views Asked by At

Herb Sutter implemented only a subset of chained comparisons in his cppfront, stating in his keynote (https://youtu.be/fJvPBHErF2U?si=RqcR661yBzcQ8r5_&t=850) that a >= b < c is "mathematically unsound". He shows three examples of chained comparisons. One would be supported but two of them would not would not be supported in c++2 even though they are supported in Python. He does not go on to expand upon the reasons other than to point out the how this decision is addressed in Python and this is related to his point about simplicity, safety and efficiency.

simplicity, safety and efficiency -- chained comparisons examples screen shot fragment

Mathematical textbooks are full of expressions like a > b < c to express a minimum or a >= b < c for a one-side minimum. What is mathematically unsound about these chained comparisons?

2

There are 2 answers

7
João Areias On

Typically we write a < b < c as a shorthand for a < b, b < c, and a < c. Assuming this is the case and <, >, <=, >= are transitive, which is usually the case, writing a < b > c would imply that a < b, b < c, and a > c, which is always false. Writing a <= b > c could be true if and only if a = b and b > c, but this is still not the interpretation that Python has.

In Python, writing a < b > c means a < b and b > c, no comparisons are made between a and c, meaning the statement could be true. Similarly, the interpretation of a <= b > c is completely different as there are many cases where a != b and the statement is still true.

print(3 < 5 > 4) # Prints `True`

While the a op c comparison in the a op b op c example is not something we can actually infer, and the correct mathematical interpretation is, in fact, a op b and b op c, this is an expectation that many people have when they see a chained comparison (as demonstrated by how unpopular the a < b > c notation is).

This notation is not technically mathematically unsound, but it is uncommon and uncomfortable. When we are habituated in thinking by the reasoning presented in the first paragraph, this notation makes us stop and think just a little bit harder even if it is by a split second, creating friction and making it harder to understand the actual logic of the algorithm. We must remember code is read quite a lot. The subversion of expectations when seeing a a < b > c comparison makes it really hard to track the code logic and could be more clearly represented with a < b and c < b

5
bolov On
d != e != f

This contains only "not equal operators" between operands. So it might be counterintuitive and unexpected that d == f can satisfy this condition. This happens because the chain is not transitive.