Lecture - 6 Left Recursion
Lecture - 6 Left Recursion
Recursion-
1. Left Recursion
2. Right Recursion
3. General Recursion
1. 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 / ∈
A → Aα / β
Then, we can eliminate left recursion by replacing the pair of productions with-
A → βA’
A’ → αA’ / ∈
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 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 / ∈
PRACTICE PROBLEMS BASED ON LEFT RECURSION ELIMINATION-
Problem-01:
A → ABd / Aa / a
B → Be / b
Solution-
A → aA’
A’ → BdA’ / aA’ / ∈
B → bB’
B’ → eB’ / ∈
Problem-02:
E→E+E/ExE/a
Solution-
E → aA
A → +EA / xEA / ∈
Problem-03:
T→TxF/F
F → id
Solution-
E → TE’
E’ → +TE’ / ∈
T → FT’
T’ → xFT’ / ∈
F → id
Problem-04:
S → (L) / a
L→L,S/S
Solution-
S → (L) / a
L → SL’
L’ → ,SL’ / ∈
Problem-05:
S → S0S1S / 01
Solution-
S → 01A
A → 0S1SA / ∈
Problem-06:
Consider the following grammar and eliminate left recursion-
S→A
A → Ad / Ae / aB / ac
B → bBc / f
Solution-
S→A
A → aBA’ / acA’
A’ → dA’ / eA’ / ∈
B → bBc / f
Problem-07:
A → AAα / β
Solution-
A → βA’
A’ → AαA’ / ∈
Problem-08:
A → Ba / Aa / c
B → Bb / Ab / d
Solution-
Step-01:
A → BaA’ / cA’
A’ → aA’ / ∈
A → BaA’ / cA’
A’ → aA’ / ∈
B → Bb / Ab / d
Step-02:
A → BaA’ / cA’
A’ → aA’ / ∈
B → Bb / BaA’b / cA’b / d
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:
X → XSb / Sa / b
S → Sb / Xa / a
Solution-
Step-01:
X → SaX’ / bX’
X’ → SbX’ / ∈
X → SaX’ / bX’
X’ → SbX’ / ∈
S → Sb / Xa / a
Step-02:
X → SaX’ / bX’
X’ → SbX’ / ∈
S → Sb / SaX’a / bX’a / a
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:
S → Aa / b
A → Ac / Sd / ∈
Solution-
Step-01:
First let us eliminate left recursion from S → Aa / b
Step-02:
S → Aa / b
A → Ac / Aad / bd / ∈
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’ / ∈
Get more notes and other study material of Theory of Automata and Computation.
Summary