Search code examples
programming-languagesconditional-statements

Chained inequality notation in programming languages


Is there a programming language that supports chained notation a < b < c to be used instead of a < b and b < c in conditional statements?

Example:

  1. if ( 2 < x < 5 )
  2. if ( 2 < x && x < 5 )

First statementlooks better to me, it's easier to understand and the compiler could use transitivity property to warn about mistakes (e.g. 5 < x < 2 would give a warning).


Solution

  • Icon does this, and it is not part of any hacky special-case "chaining"; it is part of Icon's goal-directed evaluation model. Any comparison either succeeds or fails. If it succeeds, it produces the right-hand side. So you can write

    if 0 <= i <= j < n then ...
    

    and it works exactly the way you would expect. But it works not just for comparisons but for any expression; this means you can write your own functions that "chain" in exactly the same way. I love this aspect of Icon and wish more languages could incorporate goal-directed evaluation.

    N.B. In Guido's paper introducing Python at VHLL (middle 1990s) he mentions Icon explicitly as a source of inspiration in the design of Python.