Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Language support for chained comparison operators (x < y < z)

A question was posted about chained comparison operators and how they are interpreted in different languages.

Chaining comparison operators means that (x < y < z) would be interpreted as ((x < y) && (y < z)) instead of as ((x < y) < z).

The comments on that question show that Python, Perl 6, and Mathematica support chaining comparison operators, but what other languages support this feature and why is it not more common?

A quick look at the Python documentation shows that this feature has been since at least 1996. Is there a reason more languages have not added this syntax?

A statically typed language would have problems with type conversion, but are there other reasons this is not more common?

like image 423
Alan Geleynse Avatar asked Nov 03 '10 19:11

Alan Geleynse


People also ask

Does Python allow chained comparison?

Python supports chaining of comparison operators, which means if we wanted to find out if b lies between a and c we can do a < b < c , making code super-intuitive. Python evaluates such expressions like how we do in mathematics.

Can you chain == in Python?

Chaining with the comparison operator == returns True only if all values are equal. If there is even one different value, False is returned. Be careful when using the comparison operator !=

What is the === comparison operator used for?

Equal to ( === ) — returns true if the value on the left is equal to the value on the right, otherwise it returns false .

What are the 4 Python comparison operators?

Summary. A comparison operator compares two values and returns a boolean value, either True or False . Python has six comparison operators: less than ( < ), less than or equal to ( <= ), greater than ( > ), greater than or equal to ( >= ), equal to ( == ), and not equal to ( != ).


2 Answers

It should be more common, but I suspect it is not because it makes parsing languages more complex.

Benefits:

  • Upholds the principle of least surprise
  • Reads like math is taught
  • Reduces cognitive load (see previous 2 points)

Drawbacks:

  • Grammar is more complex for the language
  • Special case syntactic sugar

As to why not, my guesses are:

  • Language author(s) didn't think of it
  • Is on the 'nice to have' list
  • Was decided that it wasn't useful enough to justify implementing
like image 77
Bruce Armstrong Avatar answered Sep 20 '22 17:09

Bruce Armstrong


The benefit is too small to justify complicating the language.

You don't need it that often, and it is easy to get the same effect cleanly with a few characters more.

like image 44
starblue Avatar answered Sep 17 '22 17:09

starblue