Download presentation
Presentation is loading. Please wait.
1
CSCI 432 Computer Science Theory
Context Free Grammars CSCI 432 Computer Science Theory
2
Why Study CFGs What is "grammar"?
What does grammar have to do with computing? Examples of grammar in computing?
3
Terminology S → bA A → aA A → e Those are three rules or productions.
The starting rule is usually the first rule listed. S and A are nonterminals. a and b are terminals. Only a single nonterminal appears on the left side of a rule.
4
Example S → bA 1 A → aA 2 A → e 3 Suppose we want to generate the word "baaa" using this grammar. S bA 1 baA 2 baaA 2 baaaA 2 baaa 3 textbook page 70
5
Non Context Free Grammar
aAb → acb How the rule for A is used depends on whether or not it is surrounded by an a and a b. Thus, that rule is not free of context.
6
Nondeterminism B → bB B → b
We cannot determine which version of B to use to generate the desired word. We have to try possibilities until we generate the desired word. Thus, using CFGs to generate words is nondeterministic. textbook page 72
7
Example 1 L(G) = {anbn} S → aSb S → e S aSb aaSbb aaaSbbb aaabbb So…
Can a CFG represent a non-regular language? L(G) = {anbn} S → aSb S → e S aSb aaSbb aaaSbbb aaabbb All regular languages can be represented with a CFG. textbook example 3.1.1
8
Example 2 a*b* S → aS S → Sb S → e
So how would we generate the word aaabb? S S aS Sb aaS aSb aaaS aaSb aaaSb aaSbb aaaSbb aaaSbb aaabb aaabb These 3 rules could also be written as: S → aS | Sb | e textbook example 3.1.2
9
Example 3 What does this grammar generate? S → aSa | bSb | e For example S aSa aaSaa aabSbaa aabaSabaa aabaabaa textbook example 3.1.3
10
Example 4 Binary string with even number of 0's. 1 S → 1S 2 S → 0A0S 3 S → e 4 A → 1A 5 A → e Try to generate the string S 0A0S 2 01A0S 4 011A0S 4 0111A0S 4 ,5
11
Practice Binary string with even number of 0's. 1 S → 1S 2 S → 0A0S 3 S → e 4 A → 1A 5 A → e Generate the string 11010 S 1S 1 11S 1 110A0S 2 1101A0S 4 11010S 3
12
Practice Use the following grammar to produce the string "the dog eats the bone". 1 S → NP VP 2 NP → the N 3 VP → V NP 4 V → eats | buries 5 N → dog | bone
13
Grammatically Correct ≠ Meaningful
We could also use this grammar to generate the string "the bone buries the dog". 1 S → NP VP 2 NP → the N 3 VP → V NP 4 V → eats | buries 5 N → dog | bone
14
Using Grammars How do we use a grammar to check the validity of data or a source code file? Bad Answer : generate lots of possibilities until you generate a match. Then you know the data matches the grammar. Good Answer : Parsing.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.