Chapter recap
A CFG has rules A → α with one variable on the left. Derivations build parse trees; trees correspond one-to-one with leftmost and with rightmost derivations. Standard grammars: aⁿbⁿ (S → aSb | ε), palindromes, balanced parentheses, #a = #b (S → aSbS | bSaS | ε), i ≠ j (equal core plus extras), unions, concatenations. A grammar is ambiguous if a string has two parse trees; some languages (aⁱbʲcᵏ, i = j or j = k) are inherently ambiguous.
Merged rule card
From 3.1.1 Context-free grammars, derivations and parse trees
- CFG: A → α, single variable on the left. CFL = L(G) for some CFG. Regular ⊂ CFL.
- Leftmost / rightmost derivations; parse tree with yield = leaves left to right.
- Trees ↔ leftmost derivations ↔ rightmost derivations (one-to-one per string).
From 3.1.2 Writing CFGs for standard languages
- Wrap: S → aSb | ε (aⁿbⁿ); ratios S → aSbb.
- Nested: outer wrap → inner wrap. Concatenation: S → XY. Union: S → S₁ | S₂. Star: S → S₁S | ε.
- Palindromes S → aSa | bSb | a | b | ε. Balanced S → SS | (S) | ε. #a = #b: S → aSbS | bSaS | ε.
- i ≠ j: S → AC | CB, C → aCb | ε, A → aA | a, B → bB | b.
From 3.1.3 Ambiguity
- Ambiguous: some w has ≥ 2 parse trees (≡ ≥ 2 leftmost derivations).
- Witnesses: E+E/E*E with id+id*id; SS with three pieces; aS|Sa with aa; dangling else.
- Fix with precedence layers E → E+T | T, T → T*F | F, F → (E) | id.
- Inherently ambiguous language: every grammar ambiguous, e.g. aⁱbʲcᵏ with i=j or j=k. No algorithm decides ambiguity in general.
Practice questions
- MCQ
L(S → aSb | aS | ε) is:
- { aⁿbⁿ }
- { aⁱbʲ : i ≥ j }
- { aⁱbʲ : i ≤ j }
- a*b*
- MSQ
Which strings are in L(S → SS | (S) | ε)?
- (()())
- )(
- ()(())
- (()
- MCQ
The grammar S → aSa | bSb | a | b is:
- ambiguous
- unambiguous
- not context-free
- regular
- NAT
With S → aSbb | ε, length of the string derived with 4 applications of S → aSbb?
Write your answer before opening the key.
- MCQ
Which proves ambiguity?
- a leftmost and a rightmost derivation of w
- two parse trees of w
- two grammars for L
- a string with a long derivation
- MSQ
Which are context-free languages?
- { aⁿbⁿ }
- palindromes
- { aⁿbᵐcᵐdⁿ }
- every regular language
- NAT
Number of parse trees of id+id+id in E → E+E | id?
Write your answer before opening the key.
- MCQ
S → aSbS | bSaS | ε generates:
- palindromes
- strings with #a = #b
- aⁿbⁿ
- (ab)*
Answer key
Reveal answers when you’re ready
- B — aS adds unmatched a’s.
- A: Extra a’s possible.
- C: Backwards.
- D: b’s cannot exceed a’s.
- AC — Balanced only.
- B: Starts with ).
- D: Unbalanced.
- B — Each palindrome has one derivation.
- A: Choices are forced by the symbols.
- C: It is a CFG.
- D: Not right/left-linear.
- 12 — a⁴b⁸.
- B — Definition.
- A: Normal for one tree.
- C: About the language, not the grammar.
- D: Irrelevant.
- ABCD — All have CFGs.
- 2 — Left or right grouping.
- B — Split at the balancing partner.
- A: abba ok but ab is not a palindrome and is generated.
- C: ba is generated.
- D: ba is generated.