Language support for chained comparison operators

2020-01-23 05:13发布

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?

5条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-01-23 05:32

Chained comparison is a feature of BCPL, since the late 1960s.

查看更多
再贱就再见
3楼-- · 2020-01-23 05:40

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
查看更多
虎瘦雄心在
4楼-- · 2020-01-23 05:43

I think ICON is the original language to have this, and in ICON it falls out of the way that booleans are handled as special 'fail' tags with all other values being treated as true.

查看更多
贪生不怕死
5楼-- · 2020-01-23 05:50

Scheme (and probably most other Lisp family languages) supports multiple comparison efficiently within its grammar:

(< x y z)

This can be considered an ordinary function application of the < function with three arguments. See 6.2.5 Numerical Operations in the specification.

Clojure supports chained comparison too.

查看更多
Juvenile、少年°
6楼-- · 2020-01-23 05:51

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.

查看更多
登录 后发表回答