Frage

In comparison, instead of using 1 < i && i < 10 can we use 1 < i < 10? As you can see the latter saves space and the readability is increased.

Is this possible in any programming language?

EDIT:

In Javascript, 1 < i < 10 will always return true regardless of what i equals. For example,
1 < 44 < 10 returns true.

War es hilfreich?

Lösung

JavaScript does not support it. For example, -3 < -2 < -1 results in false. For positive values, it sometimes "looks" like it is working, but there is implicit type conversion going on. For example, 3 < 4 < 5 gives true, but this value really comes from (3<4)<5, which is equal to true < 5, which is equal to 1 < 5 === true.

Andere Tipps

This is supported in Python:

Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Example:

1 < 2 < 3    # true (correct)  - equivalent to 1 < 2 and 2 < 3
1 < 4 < 3    # false (correct) - equivalent to 1 < 4 and 4 < 3
(1 < 4) < 3  # true ("incorrect")

3 > 2 > 1    # true (correct)  - equivalent to 3 < 2 and 2 < 1
3 > 4 > 1    # false (correct) - equivalent to 3 > 4 and 4 > 1
3 > (4 > 1)  # true ("incorrect")

This feature is merely an artifact of a particular programming language (e.g Python) and most languages (e.g. JavaScript) only treat/parse comparison operators (i.e. <) as a leftward-associative binary operators.

As such, where such syntax is even well-typed, a < b < c is generally not a "range" comparisons, but with few exceptions (e.g. Python), is parsed as (a < b) < c.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top