CH 3
CH 3
Context-Free
Grammars
Context-Free Grammars and Languages
Defn. 3.1.1 A context-free grammar is a quadruple (V, ,
P, S), where
V is a finite set of variables (non-terminals)
, the alphabet, is a finite set of terminal symbols
P is a finite set of rules of the form V (V )*, and
S V, is the start symbol
5
CFG and Languages
Design CFG for the following languages:
(i) The set { 0n1n | n 0 }.
6
CFG and Languages
Defn. 3.1.4. Let G = (V, , P, S) be a CFG and S
*
G w a
derivation. The derivation tree, DT, of S
*
G
w is an
ordered tree that can be built iteratively as follows:
(i) Initialize DT T with root S
(ii) If A x1 ... xn, where xi (V ), is a rule in the derivation
applied to rAv, then add x1 ... xn as the children of A in T
(iii) If A is a rule in the derivation applied to uAv, then add
as the only child of A in T
e.g., Fig. 3.2 for Fig. 3.1(a) S AA aA aAAA
abAAA abaAA ababAA
ababaA ababaa
Fig. 3.3 for Fig. 3.1(a)...(d)
10
Chomsky Normal Form
Theorem 4.5.2. Let G = (V, , P, S) be a CFG. There is an
algorithm to construct a grammar G’ = (V’, ’, P’, S’) in
chomsky normal form that is equivalent to G
Proof (sketch):
(i) For each rule A w, where |w| > 1, replace each terminal
symbol a w by a distinct variable Y and create new rule
Y a.
(ii) For each modified rule X w, w is either a terminal or a
string in V+. Rules in the latter form must be broken into a
sequence of rules, each of whose R.H.S. consists of two
variables.
Example 4.5.1
G1: S bS | aA A bA |
G2: S bS | A A Ab | a
S1 S2
S1 c a S2
S1 c a S2
15
…… ……
3.5 Leftmost Derivations and Ambiguity
Another example of inherently ambiguous language:
L = { anbncmdm | n, m > 0 } { anbmcmdn | n, m > 0 }
Reference:
“Ambiguity in context free languages,” S. Ginsburg and J. Ullian,
Journal of the ACM, (13)1: 62- 89, January 1966.
16