Context-Free Grammars Sipser 2.1 (pages 99 – 109)
CS 311 Fall What are we missing? So far: We know how to recognize languages –With finite state automata –As people… We know how to generate languages –With regular expressions –As people… Finite state automata and regular expressions are limited, though!
CS 311 Fall Bring back memories? In English, a grammar tells us whether a particular sentence is well formed or not For instance, “a sentence can consist of a noun phrase followed by a verb phrase” More concisely, we could write → G
CS 311 Fall Great, but what’s a noun phrase? A sentence is – → G We need to provide definitions for the newly introduced constructs and – → G
CS 311 Fall Generating well-formed sentences Grammar rules so far: – → G To complete our simple grammar, we associate actual words with the terms,, and – → G a – → G the – → G student – → G relaxes – → G studies.
CS 311 Fall Context-free grammars A context-free grammar G is a quadruple (V, Σ, R, S), where – V is a finite set called the variables – Σ is a finite set, disjoint from V, called the terminals – R is a finite subset of V × ( V ∪ Σ )* called the rules – S ∈ V is called the start symbol For any A ∈ V and u ∈ (V ∪ Σ) *, we write A → G u whenever (A, u) ∈ R
CS 311 Fall The language of a grammar If – u, v, w ∈ (V ∪ Σ)* – A → G w is a rule then –We say uAv yields uwv –Write uAv ⇒ G uwv If – u ⇒ G u1 ⇒ G u2 ⇒ G... ⇒ G uk ⇒ G v then –We write u ⇒ * G v The language of the grammar G is L(G) = {w ∈ Σ* | S ⇒ * G w}
CS 311 Fall For example… Consider G = (V, Σ, R, S), where – V={S} – Σ ={a,b} – R ={ S → G aSa | bSb | aSb | bSa | ε } Is there a grammar whose language is PAL = {w ∈ Σ* | w = reverse(w)} ?
CS 311 Fall Arithmetic expressions and parse trees Consider G = (V, Σ, R, S), where – V ={,, } – Σ ={a, +, ×, (, )} – R ={ → G + |, → G × |, → G ( ) | a } – S = What about a × a +a ?