Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Chained Comparisons #2954

Closed
evgenidb opened this issue Nov 12, 2019 · 2 comments
Closed

Proposal: Chained Comparisons #2954

evgenidb opened this issue Nov 12, 2019 · 2 comments

Comments

@evgenidb
Copy link

Allow chaining of comparison operators:
a < b <= c and a > b >= c
should compile to
a < b && b <= c and a > b && b >= c

Example:

if (0 < variable < 100) { // Do something }

This should simplify some rather common cases where a variable should be tested if it is between values.

Rules:

  • Can be chained any number of comparison operators. The examples are with 3 vars and 2 operators, but with 4 or 5 operators should be legal. Example:
    a <= b < c == d < e
    Sure it gets less and less readable as the values pile up, but it is still shorter and more readable than
    a <= b && b < c && c == d && d < e and less error prone (the user won't use || instead of && by mistake, since there is no && or || anywhere).
  • The chain should be replaced with the corresponding operators and && at compile time.
  • Allowed operators are <, <=, >, >=, and ==.
  • != should not be allowed, since it could lead to occasional confusion. For example:
    a != b != c
    Are you testing for b to be different to a and c (but a and c could be the same) or are you testing all 3 to be different? The compiler will compile to the former but it is unclear whether the user didn't mean the latter (and probably did mean the later!).
  • The operators should be compared in only one direction. For example:
    a > b < c and a < b > c should be illegal and throw a compile error.
    So if there is even a single < or <= then the user can't use > or >= in the chain. The reason is that it becomes hard to read and reason, especially if many more are chained.
@HaloFour
Copy link
Contributor

#847
#1128
#1175
#1194

Also, relational/conjunctive patterns: #2850

@YairHalberstadt
Copy link
Contributor

Closing as championed at #4108

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants