142k views
5 votes
Rewrite the BNF of example 3.4 to give precedence over * and force it to be right associative?

User Vertex
by
7.8k points

1 Answer

0 votes

Final answer:

To rewrite BNF for operator precedence and associativity, non-terminal symbols are defined to represent precedence levels, with specific rules arranged for multiplication to be right-associative. Expressions define addition and have lower precedence, while terms handle right-associative multiplication.

Step-by-step explanation:

To rewrite the BNF (Backus-Naur Form) to give precedence to the multiplication operator (*) and force it to be right-associative, the grammar needs to be adjusted so that multiplications are processed after any additions and are grouped from right to left. In BNF, this can be accomplished by defining non-terminal symbols that represent the precedence levels and by arranging the rules appropriately.

Here is an example of how you might modify the BNF to achieve this:

  • <expression> ::= <term> | <expression> '+' <term>
  • <term> ::= <factor> | <term> '*' <factor>
  • <factor> ::= '(' <expression> ')' | number

In this revised BNF, <term> takes care of the multiplications and forces them to be right-associative because each <term> can be made up of another <term> followed by a '*' and a <factor>, effectively causing the multiplications to group to the right. Additionally, <expression> defines the addition operation, and it has a lower precedence because it is listed first and does not recurse on itself for addition.

User Ganesh MB
by
7.6k points