Chapter 2 - Left Recursive
Chapter 2 - Left Recursive
Left Recursion-
A production of grammar is said to have left recursion if the leftmost variable of its
RHS is same as variable of its LHS.
A grammar containing a production having left recursion is called as Left Recursive
Grammar.
Example-
S → Sa / ∈
(Left Recursive Grammar)
Left recursion is eliminated by converting the grammar into a right recursive grammar.
Then, we can eliminate left recursion by replacing the pair of productions with-
A → βA’
A’ → αA’ / ∈
(Right Recursive Grammar)
2. Right Recursion-
A production of grammar is said to have right recursion if the rightmost variable of its
RHS is same as variable of its LHS.
A grammar containing a production having right recursion is called as Right Recursive
Grammar.
Example-
S → aS / ∈
(Right Recursive Grammar)
Right recursion does not create any problem for the Top down parsers.
Therefore, there is no need of eliminating right recursion from the grammar.
3. General Recursion-
The recursion which is neither left recursion nor right recursion is called as general
recursion.
Example-
S → aSb / ∈
Problem-01:
Solution-
Solution-
Problem-03:
Solution-
Problem-04:
Consider the following grammar and eliminate left recursion-
S → (L) / a
L→L,S/S
Solution-
Problem-05:
Solution-
Problem-06:
Solution-
The grammar after eliminating left recursion is-
S→A
A → aBA’ / acA’
A’ → dA’ / eA’ / ∈
B → bBc / f
Problem-07:
Solution-
Problem-08:
Solution-
Step-01:
First let us eliminate left recursion from A → Ba / Aa / c
Step-02:
Step-03:
Now, eliminating left recursion from the productions of B, we get the following grammar-
A → BaA’ / cA’
A’ → aA’ / ∈
B → cA’bB’ / dB’
B’ → bB’ / aA’bB’ / ∈
Problem-09:
Consider the following grammar and eliminate left recursion-
X → XSb / Sa / b
S → Sb / Xa / a
Solution-
Step-01:
Step-02:
Step-03:
Now, eliminating left recursion from the productions of S, we get the following grammar-
X → SaX’ / bX’
X’ → SbX’ / ∈
S → bX’aS’ / aS’
S’ → bS’ / aX’aS’ / ∈
Problem-10:
Solution-
Step-01:
Step-02:
Step-03:
Now, eliminating left recursion from the productions of A, we get the following grammar-
S → Aa / b
A → bdA’ / A’
A’ → cA’ / adA’ / ∈