4.6.8 · D3Theory of Computation

Worked examples — Context-free grammars (CFG) — productions, derivations, parse trees

2,462 words11 min readBack to topic

The scenario matrix

Every CFG exercise you meet is one of these case classes. We will hit each one.

Cell Case class What makes it tricky Example
C1 Balanced / nested structure needs a stack — DFAs fail Ex 1: (()())
C2 Equal-count language counting two things in lockstep Ex 2
C3 The degenerate case empty string, zero-length yield Ex 3
C4 Two-sided count / palindrome-like symmetry around a centre Ex 4:
C5 Ambiguity detection ≥2 parse trees for one string Ex 5
C6 Ambiguity removal (precedence) rewrite so each string has one tree Ex 6
C7 Leftmost = rightmost = tree ordering vs structure Ex 7
C8 Word problem (real syntax) model something real as a CFG Ex 8: if/else
C9 Exam twist — union of counts one grammar, several sub-cases Ex 9: or

Terminals we use are the actual letters like , , , . Variables are capitals like . A production means "wherever you see , you may swap in ". Recall is one swap and is "zero or more swaps".


C1 — Nested & balanced structure


C2 — Equal counts


C3 — The degenerate case: the empty string


C4 — Two-sided / non-1:1 counts


C5 — Detecting ambiguity


C6 — Removing ambiguity with precedence layers


C7 — Ordering vs structure (leftmost = rightmost = same tree)


C8 — Word problem: nested if/else (real syntax)


C9 — Exam twist: a union of two count-conditions


Active Recall

Recall (C3) Why must you always check the

/ case? Because is a real length-0 string; languages like include it at . Skipping it loses a valid member.

Recall (C5 vs C7) Two derivations exist — is the grammar ambiguous?

Only if they give two distinct parse trees (two distinct leftmost derivations). Two orderings of the same tree (Ex 7) prove nothing.

Recall (C9) Can one CFG force

AND at once for ? No — is not context-free (pumping lemma). You can do the union (or), not the intersection (and).

Recall (C6) In a precedence-layered grammar, which operator ends up nearest the root?

The lowest-precedence one (e.g. +), because only the top layer produces it, forcing higher-precedence ops into deeper subtrees.


Connections