Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left-associative operators vs Right-associative operators

If we have an expression:

a $ b @ c

$ is a left-associative operator, @ is right-associative. They have the same precedence.

How is this expression parsed? As (a $ b) @ c or as a $ (b @ c)?

like image 906
Robert Bean Avatar asked Apr 12 '13 05:04

Robert Bean


People also ask

What is a right-associative operator?

Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example: '*' and '/' have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

Which operator has associativity from right to left?

Explanation: Option 1: Unary Operators have associativity right to left in C++.

Which operator has the highest precedence?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .

Do the assignment operators have right to left or left to right associativity?

Assignment operators have right-to-left associativity.


2 Answers

This is an excellent question. While Dipstick is correct that in many languages, operator precedences and associativities are defined to avoid such a problem, there are languages in which such a situation may arise.

Haskell is such a language. It allows you to define your own infix operators, and their precedences (integer from 0 to 9) and associativity (left, right, non). It's easy to create the preconditions for the scenario you described:

infixl 5 $$
($$) :: Int -> Int -> Int
a $$ b = a + b

infixr 5 @@
(@@) :: Int -> Int -> Int
a @@ b = a * b

And then the situation itself:

uhoh = 1 $$ 2 @@ 3

This results in this error message:

Precedence parsing error
    cannot mix `$$' [infixl 5] and `@@' [infixr 5] in the same infix expression

Of course, Haskell's solution -- aborting with a parse error -- is not the only way to deal with this problem, but it is certainly a reasonable one.

For more information about operator parsing in Haskell, please see section 4.4.2 of the Haskell report.

like image 52
Matt Fenwick Avatar answered Nov 29 '22 02:11

Matt Fenwick


Operators at the same precedence are all either right associative or all left associative so the problem doesn't arise.

like image 29
Dipstick Avatar answered Nov 29 '22 02:11

Dipstick