Removing Left Recursion from CFG

5.3k Views Asked by At

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.

1

There are 1 best solutions below

3
On

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'