4

The following grammar has left recursion:

T -> Tx | TYx | YX | x
X -> xx
Y -> Yy | Yx | y

How do you go about removing left recursion. I read the wikipedia explanation, but I'm fairly new to CFGs so it did not make a lot of sense. Any help is appreciated? A plain english explanation would be even more appreciated.

Wooble
  • 87,717
  • 12
  • 108
  • 131
James Franks
  • 63
  • 1
  • 3

1 Answers1

5

In this example, you can follow Robert C. Moore's general algorithm to convert a rule with left recursion to a rule with right recursion:

A -> A a1 | A a2 | ... | b1 | b2 | ...
# converts to
A  -> b1 A' | b2 A' | ...
A' -> e | a1 A' | a2 A' | ...                 # where e = epsilon

In our first case: A=T, a1=x, a2=Yx, b1=y, b2=x... (similarly for Y)

T  -> YXT' | xT'
T' -> e | xT' | YxT'
X  -> xx
Y  -> yY'
Y' -> e | yY' | xY' 
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • isn't `YXT'` still left recursive? Likewise for `YxT'` & `YxY'`? Or am I missing something. Thanks for this. It is very helpful. – James Franks Oct 31 '12 at 17:49
  • Or is not left recursive since the left side of those elements lead to different non-terminals other than where it originates from? – James Franks Oct 31 '12 at 17:51
  • `T' -> YxT'` is right recursive but not left (there is no way to have T' on the left-hand-side). Oooops: `YxY'` was a typo (corrected to `xY'`). – Andy Hayden Oct 31 '12 at 22:15