2

This is Right Recursion Grammar:

<assign> -> <id> = <exp>
<id> -> A | B | C
<exp> -> <term> + <exp> | <temp>
<term> -> <factor> * <term> | <factor>
<factor> -> ( <exp> ) | <id>

This is Left Recursion Grammar:

<assign> -> <id> = <exp>
<id> -> A | B | C
<exp> -> <exp> + <term> | <term>
<term> -> <term> * <factor> | <factor>
<factor> -> ( <exp> ) | <id>

Will those grammar produce the same parse tree for String B + C + A? The following picture is for Left Recursion.

enter image description here

However, i draw the parse tree for the Right Recursion, it is a bit different between position of nodes. I dont know if what i am doing is correct. So I wonder that Left Recursion and Right Recursion produce two different parse tree or should be same parse tree. Please help to clarify this problem. Thanks.

kp2349
  • 107
  • 1
  • 14
  • 1
    since both grammars are different I would expect different parse trees. The right recursion would swap the addition and the single expansion on the right node (not sure if you can follow this explanation :) ). – hochl Mar 23 '16 at 15:20
  • Note: The picture you provide is for the string `A=B+C+A`. – SQL Police Mar 23 '16 at 15:52
  • Fixed. Thanks SQLPolice – kp2349 Mar 23 '16 at 15:59

2 Answers2

3

Left and right recursion will not produce identical trees.
You can see easily from the grammars that A+B+C will at the "top-level' have <term> <op> <exp> or <exp> <op> <term> ("exp" being "B+C" in one case and "A+B" in the other.

The trees will only be identical in trivial cases where all productions yield a direct match.
(E.g. A (skipping assign) would be <exp> --> <term> --> <factor> --> <id>

rpy
  • 3,953
  • 2
  • 20
  • 31
2

Since both grammars are different I would expect different parse trees. The right recursion would swap the addition and the single expansion on the node at the top that is labeled <expr> = <expr> + <term>. The right recursion grammar would expand to <expr> = <term> + <expr> so both children would be swapped.

If you are trying to write a compiler for mathematical expressions a thing that matters more is operator precedence, but not sure what you are up to.

hochl
  • 12,524
  • 10
  • 53
  • 87
  • 1
    I am learning compiler in college now. the course is principle of programming language. I hope i can write my own compiler in near future but seems it goann be long way to go. – kp2349 Mar 23 '16 at 16:02
  • I think it is easiest to write a `recursive descent parser` by hand for training purposes. You will learn a lot of things that you are missing out if you just play with `flex` and `bison` (which is nice by itself). – hochl Mar 23 '16 at 16:07