portal.cs.ku.edu.kwportal.cs.ku.edu.kw/~fatma/211/Leftmost and Rightmost... · Web viewChomsky...
Click here to load reader
Transcript of portal.cs.ku.edu.kwportal.cs.ku.edu.kw/~fatma/211/Leftmost and Rightmost... · Web viewChomsky...
Leftmost and Rightmost Derivations
Now consider the grammar G = ({S, A, B, C}, {a, b, c}, S, P) where:
S ABC
A aA | λ
B bB | λ
C cC | λ
With this grammar, there is a choice of variables to expand. Here is a sample derivation:
S ABC aABC aABcC aBcC abBcC abBc abbBc abbc
If we always expanded the leftmost variable first, we would have a leftmost derivation:
S ABC aABC aBC abBC abbBC abbC abbcC abbc
Conversely, if we always expanded the rightmost variable first, we would have a rightmost derivation:
S ABC ABcC ABc AbBc AbbBc Abbc aAbbc abbc
There are two things to notice here:
1. Different derivations result in quite different sentential forms, but 2. For a context-free grammar, it really doesn't make much difference in what order we expand
the variables.
Chomsky normal form
Transform the grammar with productions
S abAB
A baB|λ
B Baa|A|λ
into Chomsky normal form.
Solution:
1. Removing λ-productions: Here A and B are nullable variables
S abAB|abA|abB|ab
A baB|baB Baa|A|Ba|Aa|a
2. Removing unit-productionsS abAB|abA|abB|abA baB|baB Baa|baB|ba|Ba|Aa|a
There are no useless productions in the grammar.3. Introduce variables C and D to substitute terminals a and b.
S CDAB|CDA|CDB|CDA DCB|DCB BAC|DCB|DC|BC|AC|aC aD b
4. Introduce variables to shorten the right sides of the production.S EF|EA|EB|CDA GB|DCB BH|GB|DC|BC|AC|aE CDF ABG DCH ACC aD b
Now the grammar is in CNF.
Show that the following grammar is ambiguous, by producing one string in the language that hastwo different parse trees:
S aS | aSbS | λ
Solution:Consider the string aaba and the two parse trees in the figure below:
S
a S
a S b S
λ a S
λ
S
a S b S
a S a S
λ λ
Consider the grammar:
S aS | aSbS | λ
Show that the grammar is ambiguous, by giving two parse trees for the
string aab.
Solution:
S -> aSbS -> aaSbS -> aabS -> aabS -> aS -> aaSbS -> aabS -> aab
Construct PDAs that accept each of the following language.a) {aibj | 0 ≤ i ≤ j}
aλ|A bA|λ , bλ| λ
λλ|λ q0
q1