Hacker News new | ask | show | jobs
by dan-robertson 27 days ago
The point is that there is no longer a global ‘precedence number’ where the operator with the higher precedence binds tighter. Instead, it is only valid to write your example for some combinations of op1 and op2; other combinations will require explicit parentheses.

Presumably orelse is not in the table because it requires parentheses for any other operator.

1 comments

I would hope they implemented it with precedence numbers, as any other way is likely to be harder to write and lead to inconsistencies.

It’s harder to write because users will want to use expressions with more than one operator such as

   b * b - 4 * a * c
   a * b + c * d > e * f and g < h
The first expression is fine, as it uses extremely commonly known precedence rules. The second is more arguable.

However, the following expressions should be invalid in any language, and no one should write them even in languages where they are unfortunately allowed:

  a + b >> c & d && 0 % 9

  a >> 4 ? b : c & d ^ 7
Given strict left to right parsing I don't see the issue with either of those examples (setting aside that perhaps bool % int ought to trigger a type error). The second example in particular seems perfectly sensible when read this way.

Note that I view ? as a language construct rather than an operator. If for whatever reason someone insisted on including that in the strict left to right requirement the second example still works and is easy to read. I just don't like those semantics as much because the parenthesis in something like a ? ( b >> c ) : d are otherwise unnecessary. The implicit parenthesis of expr ? expr : expr seems preferable to me.

Contradicting highly ingrained precedence rules for the common operations (+, -, ×) is a huge flaw for strict left to right parsing.

And for ?:, only the part between the ? and the : is implicitly paranthesized. In "a && b ? c : d || e", you need operator precedence to decide if this is "a && (b ? c : d) || e" or "(a && b)? c : (d || e)" or any other combination. So you have to define the precedence of ? and : in relation to other operators in order to define the syntax of your language, so I think it's normal to consider it an operator as well (and I'd say the same for Python's if/else conditional expression, "a if b else c", this is not about the characters used).

Personally I don't see that as a flaw. My concern is how easy a set of rules is to understand versus get wrong at a glance. I think strict left to right is one of the better options owing to how hard it is to inadvertently misread the meaning of an expression.

> for ?:, only the part between the ? and the : is implicitly paranthesized.

That is a choice. If you treat it as an operator, yes. But you don't have to. It can be treated as a language construct. Given the grammar expr ? expr : expr the trailing portion is akin to a set of brackets or parenthesis, greedily consuming all until end of line.