140 likes | 159 Views
Context Free Grammars. CSCI 432 Computer Science Theory. Why Study CFGs. What is "grammar"? What does grammar have to do with computing? Examples of grammar in computing?. Terminology. S → bA A → aA A → e Those are three rules or productions.
E N D
Context Free Grammars CSCI 432 Computer Science Theory
Why Study CFGs • What is "grammar"? • What does grammar have to do with computing? • Examples of grammar in computing?
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.
Example S → bA1 A → aA2 A → e 3 Suppose we want to generate the word "baaa" using this grammar. S bA1 baA2 baaA2 baaaA2 baaa3 textbook page 70
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.
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
Example 1 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
Example 2 These 3 rules could also be written as: S → aS | Sb | e a*b* S → aS S → Sb S → e So how would we generate the word aaabb? S S aS Sb aaSaSb aaaSaaSb aaaSbaaSbb aaaSbbaaaSbb aaabbaaabb textbook example 3.1.2
Example 3 What does this grammar generate? S → aSa | bSb | e For example S aSa aaSaa aabSbaa aabaSabaa aabaabaa textbook example 3.1.3
Example 4 Binary string with even number of 0's. 1S → 1S 2S → 0A0S 3S → e 4A → 1A 5A → e Try to generate the string 01110. S 0A0S 2 01A0S 4 011A0S 4 0111A0S 4 01110 3,5
Practice Binary string with even number of 0's. 1S → 1S 2S → 0A0S 3S → e 4A → 1A 5A → e Generate the string 11010 S 1S 1 11S 1 110A0S 2 1101A0S 4 11010S 3 11010 5
Practice Use the following grammar to produce the string "the dog eats the bone". 1S → NP VP 2NP → the N 3VP → V NP 4V→ eats | buries 5N→ dog | bone
Grammatically Correct ≠Meaningful We could also use this grammar to generate the string "the bone buries the dog". 1S → NP VP 2NP → the N 3VP → V NP 4V→ eats | buries 5N→ dog | bone
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.