Associativity in an Expression Tree
Associativity rules can decide which repeated operator binds first when an expression has no grouping parentheses.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a subtraction
For 8 minus 3 minus 2, a left-grouped tree gives \((8-3)-2=3\). A right-grouped tree gives \(8-(3-2)=7\). See operator precedence for the related question of different operators.
Test a nonassociative example
Addition alone may conceal a tree grouping change under exact arithmetic. Select an expression with different expected results under each parser rule. Fold grouping gives another witness.[1]
Identify which operation is evaluated first
A left-associative division grammar interprets 24/6/2 as \((24/6)/2=2\). A right-associative policy yields \(24/(6/2)=8\). The root operation groups one subexpression and the remaining operand. See operator precedence.
Left tree root divides (24/6) by 2
Right tree root divides 24 by (6/2)
Different tree structures explain distinct exact arithmetic results
Distinguish associativity from precedence
Associativity resolves a chain of the same precedence. Precedence relates different operator levels. Test a chain of subtraction or division because exact addition would hide differences in grouping. Parentheses can override the grammar's usual associativity by making the intended subtree explicit.