Chained comparisons #1321
Labels
area-language
Dart language related items (some items might be better tracked at github.com/dart-lang/language).
closed-not-planned
Closed as we don't intend to take action on the reported issue
type-enhancement
A request for a change that isn't a bug
This issue was originally filed by @seaneagan
Often one needs to compare a chain of values, for example to see if they are all ordered correctly. In most programming languages it is quite ugly and unreadable:
var x = foo() , y = bar();
a < x && x <= y && y == d
however, in the following languages:
CoffeeScript: http://coffeescript.org/#comparisons
Python: http://docs.python.org/reference/expressions.html#not-in
Perl 6: http://en.wikipedia.org/wiki/Perl_6#Chained_comparisons
Standard math notation
the above can be written simply as:
a < foo() <= bar() == d
Dart mostly disallows this syntax with the exception that a relationalOperator can appear directly before an equalityOperator:
a < b == c
but it is merely interpreted as:
(a < b) == c
Such interpretations of chained comparisons are not very useful, since single comparisons return bool, which does not itself define relational operators, and for which equality operators are only used in place of XOR/XNOR, which are uncommon use cases.
Thus, this syntax should either be supported with the correct semantics (logical conjunction of each comparison), or not supported at all (which would at least allow it to be supported with the correct semantics in a later release).
Both options require merging "equalityOperator" and "relationalOperator" into "comparisonOperator", and "equalityExpression" and "relationalExpression" into "comparisonExpression".
Regardless of whether it is supported, it would a good idea to issue a static type warning if any comparison operator returns a type other than bool (or Dynamic).
The option to support chained comparisons would then additionally require something like:
comparisonExpression:
shiftExpression (isOperator type | (comparisonOperator shiftExpression)+)?
| super (comparisonOperator shiftExpression)+
;
The text was updated successfully, but these errors were encountered: