Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Lecture 5
CONTEXT-FREE GRAMMARS
(CFGs)
CONTEXT-FREE GRAMMARS
(CFGs)
Examples: CFG for { 0n1n | n > 1}
G1:
S -> 01
S -> 0S1
FORMAL DEFINITION OF
CONTEXT-FREE GRAMMAR
A context-free grammar is a 4-tuple (V, , R, S), where
1. V is a finite set called VARIABLES
is a finite set, disjoint from V, called TERMINALS
3. R is a finite set of RULES/PRODUCTIONS
4. S is the START SYMBOL
CFGs: Productions
For convenience, we abbreviate rules with the same lefthand variable into a single line
Ex: A 0A1 | B
5
FORMAL DEFINITION OF
CONTEXT-FREE GRAMMAR
Example: CFG G for { 0n1n | n > 1}.
G= (V, , R, S), where
1. V = {S}
= {0, 1}
3. R = {S -> 01,
S -> 0S1}
4. S is the start symbol
That is, the productions for A are those that have A on the left
side of the ->.
SENTENTIAL FORMS
S =>*
12
LANGUAGE OF A GRAMMAR
Note: is a legitimate
right side.
13
CONTEXT-FREE LANGUAGES
EXERCISES:
1. Using the grammar G2 defined in the previous slide, show the leftmost and rightmost
derivation with their corresponding parse trees for the string (a + a) X a
2. Given the following grammar:
<SENTENCE> <NOUN-PHRASE> <VERB-PHRASE>
<NOUN-PHRASE> <COMPLX-NOUN> | <COMPLX-NOUN> <PREP-PHRASE>
<VERB-PHRASE> <COMPLX-VERB> | <COMPLX-VERB> <PREP-PHRASE>
<PREP-PHRASE> <PREP> <COMPLX-NOUN>
<COMPLX-NOUN> <ARTICLE> <NOUN>
<COMPLX-VERB> <VERB> | <VERB> <NOUN-PHRASE>
<ARTICLE> a | the
<NOUN> boy | girl | flower
<VERB> touches | likes | sees
<PREP> with
PARSE TREES
16
AMBIGUITY
17
EXERCISES:
Given the following CFG,
E E + E | E * E | (E) | id
a.) Show that the given grammar is ambiguous by showing the
leftmost derivations and parse trees for the string id + id * id.
b.) Construct an equivalent unambiguous grammar
DESIGNING CONTEXT-FREE
GRAMMARS
Ex: { 0n1n | n 0}
DESIGNING CONTEXT-FREE
GRAMMARS
IS {a, +, X, (, )},
<FACTOR> (<EXPR>) | a
Simplified form
Form:
A BC
Aa
S
EXERCISES
1. Find CFGs that generate these regular languages over the
alphabet = {a, b}:
a) The language defined by (aaa + b)*
b) All strings with an even number of as
c) All strings with an odd number of as or an even number of
bs
2. Give a CFG that generates the non-regular language
PALINDROME (strings that read the same forward and
backward) over alphabet {a, b}.
EXERCISES
3. Given the following CFG,
G5 :
S aM
S bS
M aF
M bS
F bF
F
What is L(G5) ?
4. Find an equivalent grammar in CNF for the following CFGs:
i. S SS | A
A SS | AS | a
ii. S aA | bB
A aAA | bS | b
B bBB | aS | a