Context-Free Grammars

Lesson 13 introduces the first model that generates rather than recognizes. It covers variables, terminals, production rules, and the start variable, then one-step rewriting and why "context-free" means the surroundings are ignored, the language of a grammar, and the distinction between a sentential form and a member. It gives the four-tuple and the bar shorthand, then derivations, including the leftmost and rightmost disciplines and why they agree, and parse trees and yields with the many-derivations-one-tree relationship. A design recipe built on describing shapes recursively follows, with worked grammars for matched counts, palindromes, unions, and equal counts in any order. It closes by proving that every regular language is context-free via right-linear grammars, and showing that the containment is strict.

Subject: Theory of Computation · 121 slides · symbolic lesson

Open the interactive version of this deck · Homework for this lesson

What this lesson covers

The lesson, slide by slide

1. Context-Free Grammars

Title

Theory of Computation · Lesson 13

Stop recognizing and start generating. Four ingredients, one rewriting rule, and a class of languages that finally handles nesting.

2. What you will be able to do

Objectives

Lessons 4 to 12 mapped the regular languages completely, including what they cannot do. This lesson introduces a strictly larger class, described by generating rather than recognizing. By the end you can:

  1. Read a grammar and derive strings from it, one rewriting step at a time.
  2. Write the formal four-tuple and say which symbols are variables and which are terminals.
  1. Give leftmost and rightmost derivations, and explain why they yield the same string.
  2. Draw a parse tree and read its yield, and say what the tree records that a derivation does not.
  1. Design grammars for matched counts, palindromes and unions, using recursion deliberately.
  2. Prove every regular language is context-free, and exhibit one that is not regular.

3. What survived from Advanced Regular Properties?

Warm-up

Discussion prompt

Before we open Context-Free Grammars: without looking back, what was the main idea of Advanced Regular Properties, and what could you do by the end of it that you could not do before?

Hint: One sentence for the idea, one for the skill. If the second one is blank, that is the part to revisit.

Answer:

Lesson 12 proves languages regular without building anything. Covers the subsequence order and how it differs from the substring order, upward and downward closed languages, well-quasi-orderings and the equivalent no-descending-chain plus no-antichain characterization, Dickson's lemma on tuples with its extraction proof and why finitely many coordinates is essential, Higman's theorem with the minimal-bad-sequence sketch and the role of the finite alphabet, the finite-basis property, and the consequence that every subsequence-closed language is regular.

4. Generating Instead of Recognizing

Section

Section 1

5. A grammar produces strings; it does not test them

Concept

Every model so far took a string and answered yes or no. A grammar works the other way: it starts from a symbol and builds strings, one rewriting step at a time.

context-free grammar — A finite set of rewriting rules that replace a single variable by a string of symbols, together with a designated variable to start from.

The language of a grammar is the set of everything it can produce. Membership becomes a question about whether some sequence of rewritings reaches the string, which is a search rather than a run.

\[ S \;\Longrightarrow^{*}\; w \quad\text{means}\quad w \text{ is generated} \]

6. Break it if you can: A grammar produces strings; it does not test them

Counterexample

Discussion prompt

Every model so far took a string and answered yes or no. A grammar works the other way: it starts from a symbol and builds strings, one rewriting step at a time.

That is stated as though it always holds. Do one of two things: produce a case where it fails, or say precisely what rules such a case out. "It just does" is not on the menu.

Hint: Hunt at the extremes first — zero, one, negative, empty, equal. If every extreme survives, the reason they survive is the proof.

Answer:

The language of a grammar is the set of everything it can produce. Membership becomes a question about whether some sequence of rewritings reaches the string, which is a search rather than a run.

7. Recognizers and generators describe the same thing from opposite ends

Intuition

The shift is the same one Lesson 8 made when regular expressions arrived beside automata — and it pays off for the same reason.

AutomatonGrammar
directionconsumes a stringproduces a string
natural questionis this in the language?what do the members look like?
good atdeciding membershipdescribing structure
handles nesting?noyes

The last row is the point of the chapter. Lesson 11 proved balanced brackets are beyond finite memory; a grammar handles them in two rules.

8. Fill in: Automaton for Recognizers and generators describe the same…

Comparison

Comparison matrix

From Recognizers and generators describe the same thing from…: refill the Automaton column from what you know. The rest of the table is as it appeared.

AutomatonGrammar
directionconsumes a stringproduces a string
natural questionis this in the language?what do the members look like?
good atdeciding membershipdescribing structure
handles nesting?noyes

9. The four ingredients

Concept

A grammar is built from four things, and keeping them straight is most of the early difficulty.

  1. Variables — placeholders to be rewritten. Written as capital letters.
  2. Terminals — the actual alphabet symbols, which are never rewritten.
  3. Rules — each replaces one variable by a string of variables and terminals.
  4. Start variable — where every derivation begins.

Variables are scaffolding: they appear during construction and must all be gone by the end. A string containing a variable is unfinished, not a member of the language.

10. By analogy: The four ingredients

Analogy

Discussion prompt

Explain The four ingredients by analogy to something with no Theory of Computation in it at all — a queue, a recipe, a map, a bank balance, whatever fits. Then say where your analogy breaks.

Hint: An analogy that never breaks is not an analogy, it is the same idea wearing a hat. Find the seam — that is the part that is actually new.

Answer:

A grammar is built from four things, and keeping them straight is most of the early difficulty.

11. One rewriting step

Concept

A rule licenses one move. Find any occurrence of the rule's left-hand variable in the current string, and replace that single occurrence by the rule's right-hand side.

\[ uAv \;\Longrightarrow\; u\,\alpha\,v \quad\text{using the rule}\quad A \to \alpha \]

Everything around the chosen occurrence is left untouched — that is what context-free means. The rule applies regardless of what surrounds the variable.

The word 'free' is a restriction, not a permission. Grammars where the surroundings may constrain a rule are strictly more powerful, and are not studied here.

12. Teach it back: One rewriting step

Explain it

Discussion prompt

Explain One rewriting step to a student a year behind you. No notation, no jargon they have not met — and it still has to be true.

Hint: If your explanation needs a symbol they have never seen, you are describing the notation rather than the idea.

Answer:

A rule licenses one move. Find any occurrence of the rule's left-hand variable in the current string, and replace that single occurrence by the rule's right-hand side.

13. What has to happen first: Generate a string from a tiny grammar

Ranking

Put in order

Put the moves of Generate a string from a tiny grammar into the order they have to happen.

  1. Start from the start variable
  2. Apply the first rule
  3. Apply it again
  4. Stop with the second rule
  5. Verify the result is a legitimate member

Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. Every derivation begins with the start variable alone.

14. Generate a string from a tiny grammar

Worked example

Take a grammar with one variable and two rules, and produce a string.

\[ S \to aSb \;\mid\; \varepsilon \]

Start from the start variable

Why: Every derivation begins with the start variable alone. Nothing has been produced yet.

\[ S \]

Apply the first rule

Why: Replace the variable by the right-hand side of the recursive rule. One terminal appears on each side, with the variable still in the middle.

\[ S \Longrightarrow aSb \]

Apply it again

Why: The remaining variable is rewritten the same way, pushing the terminals outward and leaving a fresh variable in the middle.

\[ aSb \Longrightarrow aaSbb \]

Stop with the second rule

Why: Replacing the variable by the empty string removes it. No variables remain, so the derivation is finished.

\[ aaSbb \Longrightarrow aabb \]

Verify the result is a legitimate member

Why: The final string contains only terminals, so it is a genuine member rather than an unfinished form. Counting gives two a's and two b's, matching the one-a-one-b-per-step structure of the recursive rule.

\[ S \Longrightarrow^{*} aabb, \quad \#_a = \#_b = 2 \ \checkmark \]

15. Generate a string from a tiny grammar — line by line

Picture it

Animation

Shows: Each line of the worked example "Generate a string from a tiny grammar", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: The final string contains only terminals, so it is a genuine member rather than an unfinished form. Counting gives two a's and two b's, matching the one-a-one-b-per-step structure of the recursive rule.

16. Rebuild the recipe: How to apply a rule

Ranking

Put in order

These are the steps of How to apply a rule, scrambled. Put them back in order before the next slide shows you.

  1. Look at the current string and find every occurrence of a variable.
  2. Pick one occurrence and one rule whose left-hand side is that variable.
  3. Replace exactly that occurrence — not all of them — by the rule's right-hand side.
  4. Leave every other symbol untouched.
  5. Repeat until no variables remain; only then is the string finished.

Why: This is the order the recipe itself gives. Recalling the sequence without the slide in front of you is the difference between recognising the method and being able to run it — most of what goes wrong in practice is a step done out of turn.

17. How to apply a rule

Pattern

Rewriting is mechanical, and doing it the same way every time prevents the usual slips.

  1. Look at the current string and find every occurrence of a variable.
  2. Pick one occurrence and one rule whose left-hand side is that variable.
  3. Replace exactly that occurrence — not all of them — by the rule's right-hand side.
  4. Leave every other symbol untouched.
  5. Repeat until no variables remain; only then is the string finished.

Step three is the one beginners get wrong. A rule rewrites one occurrence per step, even when several are available.

18. Rule out three: Check yourself: rewriting

Elimination

Eliminate the wrong options

Starting from S, which of these strings can NOT be produced?

3 of these 4 are wrong. Strike them one at a time, and say what rules each one out before you strike the next. The survivor is the answer.

  • A. aabbb
  • B. ab
  • C. The empty string
  • D. aaabbb

Survives elimination: A

Why: Each use of the recursive rule adds exactly one a on the left and one b on the right, so every generated string has equal counts. The string aabbb has two a's and three b's, so no derivation reaches it.

19. Check yourself: rewriting

Check

Consider a grammar with the rules taking S to aSb or to the empty string.

Check your understanding

Starting from S, which of these strings can NOT be produced?

  • A. aabbb (correct)
  • B. ab
  • C. The empty string
  • D. aaabbb

Answer: A

Why: Each use of the recursive rule adds exactly one a on the left and one b on the right, so every generated string has equal counts. The string aabbb has two a's and three b's, so no derivation reaches it.

Why B tempts people
One use of the recursive rule then the empty rule gives a then b, with counts one and one.
Why C tempts people
Applying the empty rule immediately removes the start variable, producing the empty string with zero of each.
Why D tempts people
Three uses of the recursive rule then the empty rule gives three a's followed by three b's.

20. The language of a grammar

Concept

Collect every string of terminals reachable from the start variable, and you have the grammar's language.

\[ L(G) = \{\, w \in \Sigma^{*} \;:\; S \Longrightarrow^{*} w \,\} \]

context-free language — A language generated by some context-free grammar.

Note the restriction to terminals. Strings still containing variables are sentential forms — legitimate intermediate stages, but not members.

21. Plan first: A grammar for balanced brackets

Step zero

Discussion prompt

A grammar for balanced brackets — before any calculation: what is the plan? Name the moves in order, in plain English, without doing the arithmetic.

Hint: It starts with: Read each rule as a way a balanced string can look

Answer:

  1. Read each rule as a way a balanced string can look
  2. Derive a nested string
  3. Derive a sequential string
  4. Note where the unbounded memory went
  5. Verify a non-member cannot be derived

22. A grammar for balanced brackets

Worked example

The language Lesson 11 proved beyond finite automata takes two rules here.

\[ S \to (S) \;\mid\; SS \;\mid\; \varepsilon \]

Read each rule as a way a balanced string can look

Why: It is empty; or it is a balanced string wrapped in one pair; or it is two balanced strings side by side. Those three cases cover every possibility.

Derive a nested string

Why: Wrap twice, then finish with the empty rule.

\[ S \Longrightarrow (S) \Longrightarrow ((S)) \Longrightarrow (()) \]

Derive a sequential string

Why: Use the side-by-side rule first, then finish each half separately.

\[ S \Longrightarrow SS \Longrightarrow (S)S \Longrightarrow ()S \Longrightarrow ()() \]

Note where the unbounded memory went

Why: The nesting depth is carried by the number of pending variables in the sentential form, and that number is unbounded. Nothing in the grammar has to remember it explicitly.

Verify a non-member cannot be derived

Why: The string with a closing bracket before an opening one cannot appear: every rule that introduces brackets introduces them as a matched pair with the opening first, and concatenation never reorders. So no derivation produces it.

\[ (()) ,\ ()() \in L(G) \qquad )( \notin L(G) \ \checkmark \]

23. A grammar for balanced brackets — line by line

Picture it

Animation

Shows: Each line of the worked example "A grammar for balanced brackets", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: The string with a closing bracket before an opening one cannot appear: every rule that introduces brackets introduces them as a matched pair with the opening first, and concatenation never reorders. So no derivation produces it.

24. Why grammars reach past the regular languages

Intuition

The mechanism is worth naming precisely, because it is exactly what finite memory lacked.

A rule may place a variable between two terminals. Rewriting that variable then inserts more material in the middle, pushing the earlier terminals apart while keeping them paired.

\[ S \to aSb \quad\text{pairs each } a \text{ with a } b \text{ at matching depth} \]

An automaton reads left to right and cannot revisit; a grammar builds outward from the middle and never needs to. That structural difference is the whole gain.

25. The Formal Definition

Section

Section 2

26. A grammar is a four-tuple

Concept

The picture of rules on a page is convenient; the formal object has four components.

\[ G = (V, \Sigma, R, S) \]

ComponentWhat it is
Va finite set of variables
the alphabeta finite set of terminals, disjoint from the variables
Ra finite set of rules
Sone element of V, the start variable

Disjointness matters: a symbol is either rewritable or not, and it may not be both. Overlapping the two sets makes derivation ambiguous in a way nothing later can repair.

\[ V \cap \Sigma = \varnothing \]

27. What each one costs: A grammar is a four-tuple

Trade off

Comparison matrix

From A grammar is a four-tuple: every row here is a choice with a cost. Fill the What it is column, then say which row you would actually pick and what you give up for it.

ComponentWhat it is
Va finite set of variables
the alphabeta finite set of terminals, disjoint from the variables
Ra finite set of rules
Sone element of V, the start variable

28. Rules, formally

Concept

A rule pairs one variable with a string of variables and terminals — possibly the empty string.

\[ R \subseteq V \times (V \cup \Sigma)^{*} \]

The left-hand side is always a single variable. That single restriction is what makes the grammar context-free: no rule may look at the neighbours of the symbol it rewrites.

The right-hand side is unrestricted. It may mix variables and terminals freely, repeat a variable, or be empty.

29. The bar shorthand

Concept

Several rules sharing a left-hand side are written on one line, separated by a vertical bar.

\[ S \to aSb \;\mid\; SS \;\mid\; \varepsilon \]

That line is three rules, not one. The bar is a convenience of writing, exactly like the shorthands of Lesson 8, and counting rules means counting alternatives.

\[ |R| = 3 \]

When a proof says 'for each rule', it means for each alternative. Reading a barred line as a single rule is a common source of miscounted cases.

30. Guess the shape of the answer: Write the four-tuple for a grammar

Estimation

Predict first

Convert a grammar written informally into its formal tuple.

Commit before you compute: what does Write the four-tuple for a grammar come out to? A rough magnitude and the right form is enough — the point is to have something concrete to be wrong about.

Correct: Verify the two sets are disjoint and the tuple describes the same grammar

Why: A prediction you can defend turns the computation into a check rather than a leap of faith — and an answer that contradicts it is caught on the spot. No symbol appears in both sets, so the disjointness requirement holds.

31. Write the four-tuple for a grammar

Worked example

Convert a grammar written informally into its formal tuple.

\[ S \to aB \;\mid\; \varepsilon, \qquad B \to bS \]

Collect the variables

Why: Every symbol appearing on a left-hand side is a variable. Two appear here.

\[ V = \{S, B\} \]

Collect the terminals

Why: Every other symbol on a right-hand side is a terminal. The empty string is not a symbol, so it contributes nothing.

\[ \Sigma = \{a, b\} \]

Count the rules

Why: The first line carries two alternatives and the second carries one, so there are three rules in total.

\[ |R| = 3 \]

Name the start variable

Why: By convention it is the variable on the first line, and every derivation begins there.

Verify the two sets are disjoint and the tuple describes the same grammar

Why: No symbol appears in both sets, so the disjointness requirement holds. Deriving from the tuple reproduces the same strings — the empty string, then ab, then abab — confirming nothing was lost in the translation.

\[ V \cap \Sigma = \varnothing, \quad L(G) = (ab)^{*} \ \checkmark \]

32. Write the four-tuple for a grammar — line by line

Picture it

Animation

Shows: Each line of the worked example "Write the four-tuple for a grammar", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: No symbol appears in both sets, so the disjointness requirement holds. Deriving from the tuple reproduces the same strings — the empty string, then ab, then abab — confirming nothing was lost in the translation.

33. Rules that produce the empty string

Concept

A rule whose right-hand side is empty deserves its own name, because later lessons work hard to remove them.

epsilon-rule — A rule replacing a variable by the empty string, thereby deleting it.

These are what allow a derivation to terminate. Without some way to remove variables, every sentential form would keep at least one and no terminal string would ever be reached.

They are also what makes the empty string a possible member. A grammar generates the empty string exactly when its start variable can derive it.

\[ \varepsilon \in L(G) \iff S \Longrightarrow^{*} \varepsilon \]

34. Something is wrong here: treating a variable as if it were a terminal

Anomaly

Predict first

A student writes this, and it looks reasonable:

Does this grammar generate the string aSb?

It is wrong. Say what breaks — and say it before you turn the page.

Correct: Applying the recursive rule to the start variable gives a string of three symbols, so declare that string a member of the language.

Does this grammar generate the string aSb?

Why: Applying the recursive rule to the start variable gives a string of three symbols, so declare that string a member of the language.

35. Trap: treating a variable as if it were a terminal

Trap

The trap

Does this grammar generate the string aSb?

Derive one step and stop

Why: Applying the recursive rule to the start variable gives a string of three symbols, so declare that string a member of the language.

\[ S \Longrightarrow aSb \]

Report the language

Why: Collecting everything reachable in a few steps gives a set including the intermediate forms.

\[ L(G) \overset{?}{\ni} aSb \]

The fix

Does this grammar generate the string aSb?

Check whether any variables remain

Why: The middle symbol is a variable, not a terminal. A string containing a variable is a sentential form — an unfinished stage of a derivation.

\[ aSb \in (V \cup \Sigma)^{*} \quad\text{but}\quad aSb \notin \Sigma^{*} \]

Continue until only terminals remain

Why: Rewriting the remaining variable by the empty rule finishes the derivation, and the result contains only terminals.

\[ aSb \Longrightarrow ab \in L(G) \]

State the membership condition precisely

Why: The language collects only strings over the terminal alphabet. Sentential forms are legitimate stages and are never members.

\[ L(G) \subseteq \Sigma^{*} \ \checkmark \]

36. Decode the notation: Trap: treating a variable as if it were a terminal

Notation

Annotate

From Trap: treating a variable as if it were a terminal — read this one piece at a time. What is each part doing?

On: \( S \Longrightarrow aSb \)

  • Applying the recursive rule to the start variable gives a string of three symbols, so declare that string a member of the language.
  • Collecting everything reachable in a few steps gives a set including the intermediate forms.
  • The middle symbol is a variable, not a terminal. A string containing a variable is a sentential form — an unfinished stage of a derivation.

37. Naming conventions

Concept

Grammars are almost always written with the same conventions, and knowing them makes unfamiliar grammars readable at a glance.

Symbol styleMeans
capital lettersvariables
lowercase letters and digitsterminals
early Greek lettersstrings that may mix both
the first line's left-hand sidethe start variable

When a grammar breaks these conventions it will say so explicitly. Until then, a capital letter is always something still to be rewritten.

38. Fill in: Means for Naming conventions

Comparison

Comparison matrix

From Naming conventions: refill the Means column from what you know. The rest of the table is as it appeared.

Symbol styleMeans
capital lettersvariables
lowercase letters and digitsterminals
early Greek lettersstrings that may mix both
the first line's left-hand sidethe start variable

39. Reading an unfamiliar grammar

Pattern

Given a grammar you have not seen, this recovers what it generates.

  1. Identify the variables — everything appearing on a left-hand side.
  2. Identify the terminals — everything else on the right-hand sides.
  3. For each variable, read its alternatives as 'this variable can look like ... or ... or ...'.
  4. Find the rules that remove variables; those are how derivations end.
  5. Derive the two or three shortest strings by hand before generalizing.

Step four is the fastest route to understanding a grammar. A variable with no terminating alternative can never contribute to a finished string, and spotting that early saves a great deal of confusion.

40. Answer it before you see the options: Check yourself: the formal definition

Prediction

Predict first

Which of these is NOT a legal rule in a context-free grammar?

Answer it in your own words, now, with nothing to choose from. The options are on the next slide — and picking the right one off a list is an easier skill than producing it.

Correct: aB → bA

Why: The left-hand side must be a single variable. This one has a terminal alongside the variable, which would make the rule depend on the surrounding context — precisely what context-free forbids.

41. Check yourself: the formal definition

Check

Look at what the definition requires of a rule's left-hand side.

Check your understanding

Which of these is NOT a legal rule in a context-free grammar?

  • A. aB → bA (correct)
  • B. A → aAb
  • C. A → ε
  • D. A → BC

Answer: A

Why: The left-hand side must be a single variable. This one has a terminal alongside the variable, which would make the rule depend on the surrounding context — precisely what context-free forbids.

Why B tempts people
A single variable on the left and a mix of terminals and variables on the right is the standard shape of a recursive rule.
Why C tempts people
An empty right-hand side is a legal epsilon-rule, and it is how derivations terminate.
Why D tempts people
A right-hand side of two variables is legal, and it is the shape Chomsky normal form in Lesson 15 reduces everything to.

42. Derivations

Section

Section 3

43. One step and many steps

Concept

A single rewriting is written with a single arrow, and a sequence of any number of them — including none — with a starred arrow.

\[ \alpha \Longrightarrow \beta \qquad \text{versus} \qquad \alpha \Longrightarrow^{*} \beta \]

The starred relation is the reflexive transitive closure of the single-step one, exactly the construction from Lesson 2. Zero steps is allowed, so every string derives itself.

\[ \alpha \Longrightarrow^{*} \alpha \quad\text{always} \]

44. Sentential forms

Concept

sentential form — Any string of variables and terminals derivable from the start variable.

Every stage of a derivation is a sentential form. The ones containing no variables are exactly the members of the language, and they are the only stages where the derivation may stop.

\[ \text{sentential forms} \;\supseteq\; L(G) \]

A derivation may also get stuck: a sentential form whose variables have no applicable terminating alternative can never be completed. Such a branch simply produces nothing.

45. What has to be given first: Carry out a full derivation

Missing information

Discussion prompt

Derive a specific string from a grammar with two variables, writing every step.

What do you need to know — or decide — before the first line can be written? List everything the problem has to hand you.

Hint: Anything you would have to invent to get started is a thing the problem must supply.

Answer:

The only rule for the start variable replaces it with two variables.

46. Carry out a full derivation

Worked example

Derive a specific string from a grammar with two variables, writing every step.

\[ S \to AB, \qquad A \to aA \;\mid\; a, \qquad B \to bB \;\mid\; b \]

Start and expand the start variable

Why: The only rule for the start variable replaces it with two variables.

\[ S \Longrightarrow AB \]

Grow the first variable

Why: The recursive alternative adds a terminal and keeps the variable, so the block of a's can be made any length.

\[ AB \Longrightarrow aAB \Longrightarrow aaAB \]

Terminate the first variable

Why: The non-recursive alternative replaces it with a single terminal, ending that block.

\[ aaAB \Longrightarrow aaaB \]

Do the same for the second variable

Why: Grow it once, then terminate it, producing a block of b's.

\[ aaaB \Longrightarrow aaabB \Longrightarrow aaabb \]

Verify the result and read off the language

Why: The final string has only terminals, so it is a member. Every derivation must produce at least one a and at least one b, in that order, with no other constraint — so the language is a nonempty run of a's followed by a nonempty run of b's.

\[ L(G) = a^{+}b^{+}, \qquad aaabb \in L(G) \ \checkmark \]

47. Carry out a full derivation — line by line

Picture it

Animation

Shows: Each line of the worked example "Carry out a full derivation", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: The final string has only terminals, so it is a member. Every derivation must produce at least one a and at least one b, in that order, with no other constraint — so the language is a nonempty run of a's followed by a nonempty run of b's.

48. Leftmost and rightmost derivations

Concept

When several variables are available, the rewriting order is a genuine choice. Two disciplines fix it.

  1. A leftmost derivation always rewrites the leftmost variable.
  2. A rightmost derivation always rewrites the rightmost variable.

Both are ordinary derivations, subject to an extra rule about which occurrence to pick. Neither changes what can be generated — only the sequence of intermediate forms.

\[ S \Longrightarrow^{*}_{\mathrm{lm}} w \iff S \Longrightarrow^{*} w \iff S \Longrightarrow^{*}_{\mathrm{rm}} w \]

49. Derive one string two ways

Worked example

Take a grammar with a rule producing two variables, and derive the same string leftmost and rightmost.

\[ S \to AB, \qquad A \to a, \qquad B \to b \]

Expand the start variable

Why: Both disciplines agree here, since only one variable is present.

\[ S \Longrightarrow AB \]

Leftmost: rewrite the first variable first

Why: The leftmost variable is the first one, so it goes first, and the second follows.

\[ AB \Longrightarrow aB \Longrightarrow ab \]

Rightmost: rewrite the last variable first

Why: The rightmost variable is the second one, so the order is reversed.

\[ AB \Longrightarrow Ab \Longrightarrow ab \]

Compare the two sequences

Why: The intermediate forms differ, but the number of steps and the final string are identical.

\[ aB \neq Ab \quad\text{but both reach}\quad ab \]

Verify why the result had to agree

Why: Each rewriting acts on one variable and touches nothing else, so two rewritings of different variables commute. Swapping their order changes the intermediate forms and nothing else — which is exactly why both disciplines generate the same language.

\[ \text{disjoint rewrites commute} \;\Rightarrow\; \text{same final string} \ \checkmark \]

50. Derive one string two ways — line by line

Picture it

Animation

Shows: Each line of the worked example "Derive one string two ways", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: Each rewriting acts on one variable and touches nothing else, so two rewritings of different variables commute. Swapping their order changes the intermediate forms and nothing else — which is exactly why both disciplines generate the same language.

51. Why fixing the order is useful

Intuition

If the order does not matter, why insist on one? Because a canonical order removes an uninteresting kind of duplication.

Without a discipline, one string has many derivations that differ only in scheduling. With leftmost fixed, those collapse into one, and the remaining differences are structural — which is exactly what Lesson 14 needs to define ambiguity.

Parsers also pick a discipline: top-down parsers build leftmost derivations, bottom-up parsers build rightmost ones in reverse. The choice is not arbitrary in practice.

\[ \text{many derivations} \;\longrightarrow\; \text{one leftmost derivation per tree} \]

52. Plan first: Derive in a grammar with two recursive variables

Step zero

Discussion prompt

Derive in a grammar with two recursive variables — before any calculation: what is the plan? Name the moves in order, in plain English, without doing the arithmetic.

Hint: It starts with: Expand to two copies

Answer:

  1. Expand to two copies
  2. Work leftmost
  3. Finish the second copy
  4. Note how many choices were available
  5. Verify the derivation is genuinely leftmost

53. Derive in a grammar with two recursive variables

Worked example

A longer derivation, where the choice of which variable to expand really is available at every step.

\[ S \to SS \;\mid\; (S) \;\mid\; \varepsilon \]

Expand to two copies

Why: The first alternative duplicates the variable, giving two independent places to continue.

\[ S \Longrightarrow SS \]

Work leftmost

Why: Wrap the first copy in brackets, then terminate the variable inside it.

\[ SS \Longrightarrow (S)S \Longrightarrow ()S \]

Finish the second copy

Why: Wrap it and terminate it the same way.

\[ ()S \Longrightarrow ()(S) \Longrightarrow ()() \]

Note how many choices were available

Why: At the second step both copies were expandable. The leftmost discipline picked one; the rightmost discipline would have produced the same string through different intermediate forms.

Verify the derivation is genuinely leftmost

Why: At every step the variable rewritten was the leftmost one present — check each of the four steps in turn. The final string contains only terminals and is balanced, so it is a member.

\[ ()() \in L(G) \ \checkmark \]

54. Derive in a grammar with two recursive variables — line by line

Picture it

Animation

Shows: Each line of the worked example "Derive in a grammar with two recursive variables", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: At every step the variable rewritten was the leftmost one present — check each of the four steps in turn. The final string contains only terminals and is balanced, so it is a member.

55. How to find a derivation for a given string

Pattern

Deriving a specific target is a search, and a little discipline keeps it from becoming guesswork.

  1. Look at the target and identify its overall shape — nested, sequential, or a fixed pattern.
  2. Choose the start rule whose right-hand side matches that shape.
  3. Match each variable on the right against the corresponding piece of the target.
  4. Recurse on each piece independently.
  5. Stop when every piece has been reduced to terminals, then read the steps in order.

This works top-down, matching structure before symbols. Trying to derive left to right symbol by symbol usually stalls, because a grammar builds outward rather than forward.

56. Check yourself: derivations

Check

Think about what distinguishes the two disciplines.

Check your understanding

A string has a leftmost derivation and a rightmost derivation in the same grammar. What must be true?

  • A. Both produce the string, though their intermediate forms may differ (correct)
  • B. The two derivations have different lengths
  • C. The grammar must be ambiguous
  • D. The string must contain no terminals

Answer: A

Why: The disciplines constrain only which occurrence is rewritten next. Rewritings of distinct variables commute, so reordering them changes the intermediate sentential forms while leaving the final string and the number of steps untouched.

Why B tempts people
Each rule application contributes one step regardless of order, so both derivations use exactly the same number of steps.
Why C tempts people
Every string in every grammar has both a leftmost and a rightmost derivation. Ambiguity is about several parse trees, which Lesson 14 defines.
Why D tempts people
A member of the language contains only terminals, so this is backwards.

57. Parse Trees

Section

Section 4

58. The tree behind a derivation

Concept

A derivation is a sequence; a parse tree is the structure that sequence built. The tree throws away the scheduling and keeps the shape.

  1. The root is the start variable.
  2. Each internal node is a variable, and its children are the right-hand side of the rule applied to it, in order.
  3. Each leaf is a terminal, or the empty string.

Reading the leaves left to right gives the string produced, called the yield of the tree.

\[ \mathrm{yield}(T) = w \]

59. Guess the shape of the answer: Build a parse tree

Estimation

Predict first

Draw the tree for a derivation in the two-variable grammar from Section 3.

Commit before you compute: what does Build a parse tree come out to? A rough magnitude and the right form is enough — the point is to have something concrete to be wrong about.

Correct: Verify the yield matches the derived string

Why: A prediction you can defend turns the computation into a check rather than a leap of faith — and an answer that contradicts it is caught on the spot. Reading the leaves left to right gives a, then a, then b.

60. Build a parse tree

Worked example

Draw the tree for a derivation in the two-variable grammar from Section 3.

\[ S \to AB, \qquad A \to aA \;\mid\; a, \qquad B \to b \]

Place the root and its children

Why: The start variable is the root. The rule applied to it has two variables on the right, so the root has two children in that order.

\[ S \to A \; B \]

Expand the first child

Why: The recursive alternative gives it two children: a terminal and a fresh copy of the variable.

\[ A \to a \; A \]

Terminate that branch

Why: The inner variable uses the non-recursive alternative, so it has a single terminal child and the branch ends.

Expand the second child

Why: Its only rule gives one terminal child.

Verify the yield matches the derived string

Why: Reading the leaves left to right gives a, then a, then b. That is the string the corresponding derivation produced, so the tree and the derivation describe the same construction.

\[ \mathrm{yield}(T) = aab \ \checkmark \]

61. Build a parse tree — line by line

Picture it

Animation

Shows: Each line of the worked example "Build a parse tree", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: Reading the leaves left to right gives a, then a, then b. That is the string the corresponding derivation produced, so the tree and the derivation describe the same construction.

62. The tree forgets exactly the right thing

Intuition

Two derivations that differ only in the order they expanded independent variables produce the same tree. That is the point of drawing one.

The tree records which rule was applied to which occurrence, and how the pieces nest. It does not record when — because when never mattered.

So the tree is the canonical object. Derivations are one way to write a tree down linearly, and there are usually several such ways for a single tree.

\[ \text{many derivations} \;\longrightarrow\; \text{one tree} \]

63. One tree, many derivations — but one of each discipline

Concept

The relationship is worth stating precisely, because Lesson 14's definition of ambiguity depends on it.

ObjectHow many
derivations of a given treegenerally several
leftmost derivations of a given treeexactly one
rightmost derivations of a given treeexactly one
trees for a given stringone, or several — that is the question

Because a tree has exactly one leftmost derivation, counting trees and counting leftmost derivations are the same task. That equivalence is used constantly.

64. Which is which, by How many

Discrimination

Sort into buckets

Sort these by How many, from memory, without looking back at One tree, many derivations — but one of each…. Telling them apart on the spot is the skill; the table is only where the answer happens to be written down.

generally several
derivations of a given tree
exactly one
leftmost derivations of a given tree; rightmost derivations of a given tree
one, or several — that is the question
trees for a given string
g1
How many is "generally several" for derivations of a given tree — that is what the table on "One tree, many derivations — but one of…" records, and it is the single property separating this group from the rest.
g2
How many is "exactly one" for leftmost derivations of a given tree, rightmost derivations of a given tree — that is what the table on "One tree, many derivations — but one of…" records, and it is the single property separating this group from the rest.
g3
How many is "one, or several — that is the question" for trees for a given string — that is what the table on "One tree, many derivations — but one of…" records, and it is the single property separating this group from the rest.

65. What has to happen first: Count the derivations of one tree

Ranking

Put in order

Put the moves of Count the derivations of one tree into the order they have to happen.

  1. Draw the tree
  2. Fix the first step
  3. Count the orders for the remaining two
  4. Identify which is which
  5. Verify both yield the same tree

Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. Root with two children, each expanding to one terminal.

66. Count the derivations of one tree

Worked example

Make the many-to-one relationship concrete on the smallest interesting tree.

\[ S \to AB, \qquad A \to a, \qquad B \to b \]

Draw the tree

Why: Root with two children, each expanding to one terminal. Three rule applications in total.

Fix the first step

Why: The root must be expanded first, since nothing else exists yet. No choice there.

Count the orders for the remaining two

Why: The two children are independent and either may be expanded first, so there are two orders.

\[ 2! = 2 \text{ derivations} \]

Identify which is which

Why: Expanding the left child first is the leftmost derivation; expanding the right child first is the rightmost one. Here those are the only two.

Verify both yield the same tree

Why: Both orders apply the same three rules to the same three occurrences, so the parent-child structure is identical. Only the sequence differs, confirming that the tree is what the two derivations share.

\[ \text{2 derivations} \;\longrightarrow\; \text{1 tree} \ \checkmark \]

67. Count the derivations of one tree — line by line

Picture it

Animation

Shows: Each line of the worked example "Count the derivations of one tree", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: Both orders apply the same three rules to the same three occurrences, so the parent-child structure is identical. Only the sequence differs, confirming that the tree is what the two derivations share.

68. Structure carries meaning

Concept

Parse trees matter beyond bookkeeping: for many grammars the tree is the interpretation.

In an arithmetic grammar, the tree records which operations group with which operands. Two different trees for one string are two different meanings, not two spellings of one.

That is why parsers return trees rather than yes-or-no answers, and why the ambiguity question of Lesson 14 is a practical concern rather than a curiosity.

\[ \text{tree} \;\longrightarrow\; \text{meaning} \]

69. State the rule before it runs: Two trees for one string

Hypothesis

Predict first

Two trees for one string is about to be worked. State your hypothesis first: which rule or definition decides this one, and what is the first move it forces? Then watch whether the example agrees with you.

Correct: Take a string with three bracket pairs in a row

Why: The target is three empty pairs side by side.

A hypothesis you wrote down is falsifiable; a vague sense of how it will go is not. If the example opens somewhere else, that gap is the thing worth chasing.

70. Two trees for one string

Worked example

A preview of ambiguity, which Lesson 14 treats properly.

\[ S \to SS \;\mid\; (S) \;\mid\; \varepsilon \]

Take a string with three bracket pairs in a row

Why: The target is three empty pairs side by side.

\[ w = ()()() \]

Build one tree grouping to the left

Why: Apply the duplicating rule so the first two pairs form one subtree and the third stands alone.

Build another grouping to the right

Why: Apply the same rule so the first pair stands alone and the last two form one subtree.

Compare

Why: Both trees have the same yield, and their internal structure differs. So this grammar assigns the string more than one structure.

Verify both trees are legitimate

Why: Each uses only rules of the grammar, each has the start variable at its root, and each yields the target string. Nothing is wrong with either — the grammar simply admits both, which is exactly what ambiguity means.

\[ \mathrm{yield}(T_1) = \mathrm{yield}(T_2) = ()()() , \quad T_1 \neq T_2 \ \checkmark \]

71. Two trees for one string — line by line

Picture it

Animation

Shows: Each line of the worked example "Two trees for one string", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: Each uses only rules of the grammar, each has the start variable at its root, and each yields the target string. Nothing is wrong with either — the grammar simply admits both, which is exactly what ambiguity means.

72. Without one step: Drawing a parse tree from a derivation

Constraint

Discussion prompt

Run Drawing a parse tree from a derivation with this step confiscated:

Find the node for that occurrence and give it one child per symbol of the rule's right-hand side.

Is it still possible? If it is, say what takes its place and what it costs you. If it is not, say exactly what that step was providing that nothing else does.

Hint: A step you can drop for free was never load-bearing. If you cannot drop it, name the thing that goes wrong the moment it is gone.

Answer:

  1. Write the start variable as the root.
  2. Take the derivation steps in order; each rewrites one occurrence.
  3. Find the node for that occurrence and give it one child per symbol of the rule's right-hand side.
  4. An epsilon-rule gives a single child marked as the empty string.
  5. When the derivation ends, every leaf is a terminal or an empty-string marker.

73. Drawing a parse tree from a derivation

Pattern

Turning a written derivation into a tree is mechanical.

  1. Write the start variable as the root.
  2. Take the derivation steps in order; each rewrites one occurrence.
  3. Find the node for that occurrence and give it one child per symbol of the rule's right-hand side.
  4. An epsilon-rule gives a single child marked as the empty string.
  5. When the derivation ends, every leaf is a terminal or an empty-string marker.

Reading the leaves left to right must reproduce the derived string. If it does not, a step was attached to the wrong node.

74. Where does it stop working: Drawing a parse tree from a derivation

Edge cases

Discussion prompt

Drawing a parse tree from a derivation works on the cases you have just seen. Push it to the edge: what is the most degenerate input it still handles — empty, zero, one item, everything equal — and what is the first case where it stops being true? Name the case, not just "it breaks".

Hint: Try the smallest legal input, then the largest, then the one where two things collide. Methods are specified at their edges; the middle takes care of itself.

Answer:

Turning a written derivation into a tree is mechanical.

75. How sure are you: Check yourself: parse trees

Commit first

Predict first

Two different derivations of the same string produce the same parse tree. What did they differ in?

Commit to an answer, then rate it — certain, fairly sure, or guessing — and write the rating down before you turn the page.

Correct: Only the order in which independent variables were expanded

Why: A tree records which rule was applied to which occurrence and how the results nest. Two derivations sharing a tree therefore applied the same rules to the same occurrences, and could only have differed in the scheduling.

The rating matters as much as the answer: confident-and-wrong is the combination that survives revision, because nothing about it feels like it needs revisiting.

76. Check yourself: parse trees

Check

Think about what the tree records and what it discards.

Check your understanding

Two different derivations of the same string produce the same parse tree. What did they differ in?

  • A. Only the order in which independent variables were expanded (correct)
  • B. Which rules were applied
  • C. The string they produced
  • D. The start variable used

Answer: A

Why: A tree records which rule was applied to which occurrence and how the results nest. Two derivations sharing a tree therefore applied the same rules to the same occurrences, and could only have differed in the scheduling.

Why B tempts people
Different rules would give different children somewhere, producing a different tree.
Why C tempts people
The yield of a tree is determined by the tree, so derivations sharing a tree produce the same string.
Why D tempts people
The start variable is fixed by the grammar and is always the root, so it cannot differ.

77. Designing Grammars

Section

Section 5

78. The design recipe

Pattern

Designing a grammar is answering one question, just as designing a machine was — but the question is different.

  1. Ask: what does a member of this language look like, described recursively?
  2. Write one alternative per shape a member can have.
  3. Use a variable wherever a smaller member of the same kind can appear.
  4. Make sure at least one alternative contains no variables, so derivations can end.
  5. Check the shortest member, and one member of each shape.

Step four is the one that gets forgotten. A variable whose every alternative mentions a variable can never be eliminated, and contributes nothing to the language.

79. Recursion is the engine

Concept

Every infinite context-free language needs a variable that can eventually reproduce itself, and where that recursion sits determines what the grammar can do.

Shape of ruleEffectReaches past regular?
variable at the right endbuilds left to rightno
variable at the left endbuilds right to leftno
variable in the middlebuilds outward, pairingyes
two variablesbranches into independent partsyes

The third and fourth rows are what finite automata cannot imitate. The first two correspond exactly to the regular languages, as Section 6 proves.

80. Which is which, by Reaches past regular?

Discrimination

Sort into buckets

Sort these by Reaches past regular?, from memory, without looking back at Recursion is the engine. Telling them apart on the spot is the skill; the table is only where the answer happens to be written down.

no
variable at the right end; variable at the left end
yes
variable in the middle; two variables
g1
Reaches past regular? is "no" for variable at the right end, variable at the left end — that is what the table on "Recursion is the engine" records, and it is the single property separating this group from the rest.
g2
Reaches past regular? is "yes" for variable in the middle, two variables — that is what the table on "Recursion is the engine" records, and it is the single property separating this group from the rest.

81. Plan first: Design a grammar for matched counts

Step zero

Discussion prompt

Design a grammar for matched counts — before any calculation: what is the plan? Name the moves in order, in plain English, without doing the arithmetic.

Hint: It starts with: Describe a member recursively

Answer:

  1. Describe a member recursively
  2. Write one alternative per shape
  3. Check the recursion terminates
  4. See why the counts must match
  5. Verify on three members and one non-member

82. Design a grammar for matched counts

Worked example

Build a grammar for the language Lesson 11 proved non-regular.

\[ L = \{\, a^{n}b^{n} : n \ge 0 \,\} \]

Describe a member recursively

Why: A member is either empty, or it is an a, then a shorter member, then a b. Those two shapes cover everything.

Write one alternative per shape

Why: The empty case needs no variable; the recursive case wraps the variable in a matching pair.

\[ S \to aSb \;\mid\; \varepsilon \]

Check the recursion terminates

Why: The second alternative contains no variable, so every derivation can end. Each use of the first alternative strictly increases the terminals present, so no derivation is forced to loop.

See why the counts must match

Why: The only rule introducing terminals introduces exactly one of each, on opposite sides. So the counts are equal after every step, and remain equal at the end.

Verify on three members and one non-member

Why: The empty string, ab and aabb are all derivable by zero, one and two uses of the recursive rule. The string aab is not: it would need two a's and two b's by the counting argument, so no derivation reaches it.

\[ \varepsilon,\ ab,\ aabb \in L(G) \qquad aab \notin L(G) \ \checkmark \]

83. Design a grammar for matched counts — line by line

Picture it

Animation

Shows: Each line of the worked example "Design a grammar for matched counts", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: The second alternative contains no variable, so every derivation can end. Each use of the first alternative strictly increases the terminals present, so no derivation is forced to loop.

84. Design a grammar for palindromes

Worked example

Another language proved non-regular in Lesson 11, over a two-symbol alphabet.

\[ L = \{\, w : w = w^{R} \,\} \]

Describe a member recursively

Why: A palindrome is empty, or a single symbol, or a symbol followed by a shorter palindrome followed by the same symbol.

Write the alternatives

Why: Two base cases per symbol plus the empty case, and one wrapping alternative per symbol.

\[ S \to aSa \;\mid\; bSb \;\mid\; a \;\mid\; b \;\mid\; \varepsilon \]

Explain why both base cases are needed

Why: The wrapping rules always add two symbols, so they alone produce only even lengths. The single-symbol alternatives supply the odd centre.

Check the shortest members of each parity

Why: The empty string comes from the empty alternative and has even length; a single symbol comes from a one-symbol alternative and has odd length.

Verify on one string of each parity and one non-member

Why: The strings abba and aba are both derivable, wrapping outward from the empty and single-symbol centres respectively. The string ab is not: wrapping requires matching outer symbols, and its two symbols differ.

\[ abba,\ aba,\ \varepsilon \in L(G) \qquad ab \notin L(G) \ \checkmark \]

85. Design a grammar for palindromes — line by line

Picture it

Animation

Shows: Each line of the worked example "Design a grammar for palindromes", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: The empty string comes from the empty alternative and has even length; a single symbol comes from a one-symbol alternative and has odd length.

86. Union by alternatives

Concept

Combining grammars is easier than combining machines, and the three regular operations all have one-line answers.

OperationConstruction
uniona fresh start variable with one alternative per grammar
concatenationa fresh start variable whose single rule is the two old starts in sequence
stara fresh start variable that is either empty or itself followed by an old start

\[ S \to S_1 \;\mid\; S_2, \qquad S \to S_1S_2, \qquad S \to SS_1 \;\mid\; \varepsilon \]

Each needs the two variable sets renamed apart first, exactly as the machine constructions of Lesson 7 needed disjoint state sets. Lesson 19 proves all three correct.

87. What has to be given first: Design a grammar for a union

Missing information

Discussion prompt

Combine two languages, each already understood, into one grammar.

What do you need to know — or decide — before the first line can be written? List everything the problem has to hand you.

Hint: Anything you would have to invent to get started is a thing the problem must supply.

Answer:

The first is the matched-counts grammar. The second pairs each a with two b's.

88. Design a grammar for a union

Worked example

Combine two languages, each already understood, into one grammar.

\[ L = \{a^{n}b^{n}\} \;\cup\; \{a^{n}b^{2n}\} \]

Write a grammar for each part separately

Why: The first is the matched-counts grammar. The second pairs each a with two b's.

\[ A \to aAb \;\mid\; \varepsilon, \qquad B \to aBbb \;\mid\; \varepsilon \]

Check the variable sets are disjoint

Why: They use different variable names already, so nothing needs renaming.

Add a fresh start variable

Why: One alternative per part, so a derivation commits to one branch immediately and stays there.

\[ S \to A \;\mid\; B \]

Confirm no derivation can mix the branches

Why: After the first step only one of the two variables is present, and neither grammar mentions the other's variables. So the branches cannot interact.

Verify on a member of each part and a non-member

Why: The string aabb comes from the first branch and abb from the second. The string abbb belongs to neither part — one a needs either one or two b's — and no derivation produces it.

\[ aabb,\ abb \in L(G) \qquad abbb \notin L(G) \ \checkmark \]

89. Design a grammar for a union — line by line

Picture it

Animation

Shows: Each line of the worked example "Design a grammar for a union", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: They use different variable names already, so nothing needs renaming.

90. Think about shape, not about scanning

Intuition

The commonest design failure is importing habits from Lesson 4, where the question was what to remember while reading left to right.

A grammar never reads. It describes what a finished string looks like, from the outside in. So the useful question is 'what are the possible shapes of a member', and each shape becomes one alternative.

When a language ties two distant positions together — matched counts, symmetry, nesting — put a variable between them and let the rule place both at once. That single move solves most design problems in this chapter.

\[ \text{tie two positions} \;\Rightarrow\; \text{one rule places both} \]

91. Guess the shape of the answer: Design for equal counts in any order

Estimation

Predict first

Harder than matched counts, because the symbols may interleave arbitrarily.

Commit before you compute: what does Design for equal counts in any order come out to? A rough magnitude and the right form is enough — the point is to have something concrete to be wrong about.

Correct: Verify on three members and one non-member

Why: A prediction you can defend turns the computation into a check rather than a leap of faith — and an answer that contradicts it is caught on the spot. The empty string, ab and abba all derive.

92. Design for equal counts in any order

Worked example

Harder than matched counts, because the symbols may interleave arbitrarily.

\[ L = \{\, w \in \{a,b\}^{*} : \#_a(w) = \#_b(w) \,\} \]

Describe a member recursively

Why: A balanced string is empty, or it is two balanced strings joined, or it is a balanced string wrapped in a matching pair — in either order of the pair.

Write the alternatives

Why: One empty case, one joining case, and two wrapping cases for the two orders.

\[ S \to aSbS \;\mid\; bSaS \;\mid\; \varepsilon \]

Check the counting invariant

Why: Every alternative that adds terminals adds exactly one a and one b, so equality is preserved at every step.

Check the interleaving really is reachable

Why: The string abba comes from the first alternative with the inner variable empty and the trailing variable producing ba. So orders other than all-a-then-all-b are genuinely generated.

Verify on three members and one non-member

Why: The empty string, ab and abba all derive. The string aab has two a's and one b, so the invariant rules it out and no derivation reaches it.

\[ \varepsilon,\ ab,\ abba,\ baab \in L(G) \qquad aab \notin L(G) \ \checkmark \]

93. Design for equal counts in any order — line by line

Picture it

Animation

Shows: Each line of the worked example "Design for equal counts in any order", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: Every alternative that adds terminals adds exactly one a and one b, so equality is preserved at every step.

94. Answer it before you see the options: Check yourself: design

Prediction

Predict first

A grammar has the single rule taking A to aAb. What is its language?

Answer it in your own words, now, with nothing to choose from. The options are on the next slide — and picking the right one off a list is an easier skill than producing it.

Correct: The empty language — no derivation can ever finish

Why: Every alternative for the variable reintroduces that same variable, so no sentential form ever loses its last variable. No string of terminals is ever reached, and the language is empty.

95. Check yourself: design

Check

Think about what makes a derivation able to finish.

Check your understanding

A grammar has the single rule taking A to aAb. What is its language?

  • A. The empty language — no derivation can ever finish (correct)
  • B. The strings of matched a's and b's
  • C. The empty string only
  • D. Every string of a's followed by b's

Answer: A

Why: Every alternative for the variable reintroduces that same variable, so no sentential form ever loses its last variable. No string of terminals is ever reached, and the language is empty.

Why B tempts people
That would need a terminating alternative, such as the variable going to the empty string. Without one the recursion never bottoms out.
Why C tempts people
Producing the empty string would require a rule with an empty right-hand side, and there is none.
Why D tempts people
Even the counts would be forced to match, but the more basic problem is that no derivation terminates at all.

96. Building blocks worth memorizing

Concept

A handful of rule shapes cover most grammars you will need to write.

Shape wantedRule
any number of copies of a blockthe variable goes to the block then itself, or to empty
matched pairs, nestedthe variable goes to one symbol, itself, the partner symbol
two independent partsthe variable goes to two variables
a choice between shapesone alternative per shape
exactly one occurrence of a markerput the marker in a rule used exactly once

Combining these covers every design in this chapter, and most of the ones in Lesson 14.

97. What each one costs: Building blocks worth memorizing

Trade off

Comparison matrix

From Building blocks worth memorizing: every row here is a choice with a cost. Fill the Rule column, then say which row you would actually pick and what you give up for it.

Shape wantedRule
any number of copies of a blockthe variable goes to the block then itself, or to empty
matched pairs, nestedthe variable goes to one symbol, itself, the partner symbol
two independent partsthe variable goes to two variables
a choice between shapesone alternative per shape
exactly one occurrence of a markerput the marker in a rule used exactly once

98. Grammars and the Regular Languages

Section

Section 6

99. Every regular language is context-free

Concept

The new class contains the old one, and the proof is a direct translation from machines to grammars.

Given a machine, make one variable per state. For each arrow, add a rule sending the source's variable to the arrow's symbol followed by the destination's variable. For each accepting state, add an alternative sending its variable to the empty string.

\[ q \xrightarrow{\,a\,} p \;\Longrightarrow\; V_q \to a\,V_p, \qquad q \in F \;\Longrightarrow\; V_q \to \varepsilon \]

The start variable corresponds to the start state. A derivation then mirrors a run of the machine exactly, one rule per symbol read.

100. Teach it back: Every regular language is context-free

Explain it

Discussion prompt

Explain Every regular language is context-free to a student a year behind you. No notation, no jargon they have not met — and it still has to be true.

Hint: If your explanation needs a symbol they have never seen, you are describing the notation rather than the idea.

Answer:

The new class contains the old one, and the proof is a direct translation from machines to grammars.

101. Plan first: Convert a machine to a grammar

Step zero

Discussion prompt

Convert a machine to a grammar — before any calculation: what is the plan? Name the moves in order, in plain English, without doing the arithmetic.

Hint: It starts with: Make one variable per state

Answer:

  1. Make one variable per state
  2. Turn each arrow into a rule
  3. Add a terminating alternative for each accepting state
  4. Derive a string and compare with a run
  5. Verify a rejected string cannot be derived

102. Convert a machine to a grammar

Worked example

Translate the two-state machine for strings ending in 1.

\[ \delta(q_0,0)=q_0, \; \delta(q_0,1)=q_1, \; \delta(q_1,0)=q_0, \; \delta(q_1,1)=q_1, \; F = \{q_1\} \]

Make one variable per state

Why: Two states, so two variables. The one for the start state is the start variable.

\[ V = \{V_0, V_1\} \]

Turn each arrow into a rule

Why: Four arrows, so four rules, each consuming one terminal and moving to the destination's variable.

\[ V_0 \to 0V_0 \;\mid\; 1V_1, \qquad V_1 \to 0V_0 \;\mid\; 1V_1 \]

Add a terminating alternative for each accepting state

Why: Only the second state is accepting, so only its variable may vanish.

\[ V_1 \to \varepsilon \]

Derive a string and compare with a run

Why: Deriving 101 uses the rules for 1, 0 and 1 in order, then terminates — exactly the arrows the machine follows on that input.

\[ V_0 \Longrightarrow 1V_1 \Longrightarrow 10V_0 \Longrightarrow 101V_1 \Longrightarrow 101 \]

Verify a rejected string cannot be derived

Why: The string 10 would leave the derivation at the start state's variable, which has no terminating alternative, so it can never finish. That matches the machine rejecting 10, and confirms the translation is faithful.

\[ 101 \in L(G), \qquad 10 \notin L(G) \ \checkmark \]

103. Convert a machine to a grammar — line by line

Picture it

Animation

Shows: Each line of the worked example "Convert a machine to a grammar", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: The string 10 would leave the derivation at the start state's variable, which has no terminating alternative, so it can never finish. That matches the machine rejecting 10, and confirms the translation is faithful.

104. Right-linear grammars

Concept

right-linear grammar — A grammar in which every rule's right-hand side is a string of terminals followed by at most one variable, and that variable is last.

The translation above always produces such a grammar. The converse also holds: every right-linear grammar can be turned back into a machine, with one state per variable.

So the right-linear grammars generate exactly the regular languages. The recursion sitting at the right end is precisely what corresponds to reading forward without ever revisiting.

\[ \text{right-linear} \;\equiv\; \text{regular} \]

105. Term to definition: Context-Free Grammars

Matching

Match the pairs

Match each term to the definition this lesson gave it — not the one you would guess from the word.

  • t1. context-free grammar
  • t2. context-free language
  • t3. epsilon-rule
  • t4. sentential form
  • t5. right-linear grammar
  • d1. A finite set of rewriting rules that replace a single variable by a string of symbols, together with a designated variable to start from.
  • d2. A language generated by some context-free grammar.
  • d3. A rule replacing a variable by the empty string, thereby deleting it.
  • d4. Any string of variables and terminals derivable from the start variable.
  • d5. A grammar in which every rule's right-hand side is a string of terminals followed by at most one variable, and that variable is last.

Why: These are the working definitions of context-free grammar, context-free language, epsilon-rule, sentential form, right-linear grammar as Context-Free Grammars uses them. Pairing them correctly is the test of whether you could state each one with the slide switched off.

106. Why the containment is strict

Intuition

The regular languages sit inside the context-free ones, and the gap is exactly the languages needing a variable in the middle.

A right-linear rule puts the variable last, so everything already produced is finished and can never be added to on the left. That is the left-to-right discipline of a machine, written as a grammar.

Allowing the variable in the middle breaks that discipline: material can still be added on both sides of what has already been produced. Lesson 11 proved no machine can imitate this, so the containment is strict.

\[ \text{regular} \;\subsetneq\; \text{context-free} \]

107. By analogy: Why the containment is strict

Analogy

Discussion prompt

Explain Why the containment is strict by analogy to something with no Theory of Computation in it at all — a queue, a recipe, a map, a bank balance, whatever fits. Then say where your analogy breaks.

Hint: An analogy that never breaks is not an analogy, it is the same idea wearing a hat. Find the seam — that is the part that is actually new.

Answer:

The regular languages sit inside the context-free ones, and the gap is exactly the languages needing a variable in the middle.

108. What has to happen first: Exhibit a context-free language that is not regular

Ranking

Put in order

Put the moves of Exhibit a context-free language that is not regular into the order they have to happen.

  1. Take the matched-counts language
  2. Recall it is not regular
  3. Conclude the containment is strict
  4. Note that the grammar's recursion is not right-linear
  5. Verify the two facts are independent

Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. Its grammar was written in Section 5, so it is context-free by exhibition.

109. Exhibit a context-free language that is not regular

Worked example

Put the two halves together to prove the containment strict, rather than merely asserting it.

Take the matched-counts language

Why: Its grammar was written in Section 5, so it is context-free by exhibition.

\[ S \to aSb \;\mid\; \varepsilon \]

Recall it is not regular

Why: Lesson 11 proved this by pumping: choosing p a's followed by p b's forces the middle part into the a's, and pumping unbalances the counts.

Conclude the containment is strict

Why: A language in the second class but not the first witnesses that the classes differ. Combined with the translation above, the containment is strict.

\[ \text{regular} \;\subsetneq\; \text{context-free} \]

Note that the grammar's recursion is not right-linear

Why: The recursive rule places the variable between two terminals, so it violates the right-linear restriction — which is consistent with the language being outside the regular class.

Verify the two facts are independent

Why: One is an exhibition and the other an impossibility proof, established by completely different means. Neither could substitute for the other, which is why both chapters were needed.

\[ \exists G : L = L(G) \quad\text{and}\quad \lnot\exists M : L = L(M) \ \checkmark \]

110. Exhibit a context-free language that is not regular — line by line

Picture it

Animation

Shows: Each line of the worked example "Exhibit a context-free language that is not regular", appearing one at a time.

The same working the example does, in the order a tutor would write it.

Takeaway: One is an exhibition and the other an impossibility proof, established by completely different means. Neither could substitute for the other, which is why both chapters were needed.

111. The hierarchy so far

Concept

Two classes are now in place, and the course adds two more before it finishes.

ClassGenerated byRecognized byExample beyond the previous
regularright-linear grammarsfinite automata—
context-freecontext-free grammarspushdown automata, Lesson 16matched counts

The recognizer for this class arrives in Lesson 16 and is a machine with a stack. Lesson 17 proves the grammar and the machine equivalent, exactly as Lessons 8 and 9 did for the regular class.

112. Fill in: Recognized by for The hierarchy so far

Comparison

Comparison matrix

From The hierarchy so far: refill the Recognized by column from what you know. The rest of the table is as it appeared.

ClassGenerated byRecognized byExample beyond the previous
regularright-linear grammarsfinite automata—
context-freecontext-free grammarspushdown automata, Lesson 16matched counts

113. Rule out three: Check yourself: the containment

Elimination

Eliminate the wrong options

Which grammar generates a language that is NOT regular?

3 of these 4 are wrong. Strike them one at a time, and say what rules each one out before you strike the next. The survivor is the answer.

  • A. S → aSb | ε
  • B. S → aS | bS | ε
  • C. S → aaS | ε
  • D. S → aS | b

Survives elimination: A

Why: This rule places the variable between two terminals, pairing each a with a b at matching depth. The language is the matched-counts language, which Lesson 11 proved has no finite automaton.

114. Check yourself: the containment

Check

Recall which rule shape corresponds to a machine.

Check your understanding

Which grammar generates a language that is NOT regular?

  • A. S → aSb | ε (correct)
  • B. S → aS | bS | ε
  • C. S → aaS | ε
  • D. S → aS | b

Answer: A

Why: This rule places the variable between two terminals, pairing each a with a b at matching depth. The language is the matched-counts language, which Lesson 11 proved has no finite automaton.

Why B tempts people
Every right-hand side ends with the variable, so this is right-linear and generates every string over the two symbols — plainly regular.
Why C tempts people
Right-linear again, generating the runs of a's of even length, which a two-state machine recognizes.
Why D tempts people
Right-linear, generating any number of a's followed by a single b. A three-state machine handles it.

115. Rebuild the recipe: Choosing between a grammar and a machine

Ranking

Put in order

These are the steps of Choosing between a grammar and a machine, scrambled. Put them back in order before the next slide shows you.

  1. Describing what members look like, or specifying a syntax: use a grammar.
  2. Deciding membership mechanically: use the machine, or a parser built from the grammar.
  3. Proving a closure property: usually the grammar, since alternatives compose freely.
  4. Proving a language is not in the class: neither — that needs Lesson 18's pumping lemma.
  5. Recovering structure or meaning from a string: the grammar, since it yields a parse tree.

Why: This is the order the recipe itself gives. Recalling the sequence without the slide in front of you is the difference between recognising the method and being able to run it — most of what goes wrong in practice is a step done out of turn.

116. Choosing between a grammar and a machine

Pattern

Both describe the same class from Lesson 17 onward, so the choice is about the task.

  1. Describing what members look like, or specifying a syntax: use a grammar.
  2. Deciding membership mechanically: use the machine, or a parser built from the grammar.
  3. Proving a closure property: usually the grammar, since alternatives compose freely.
  4. Proving a language is not in the class: neither — that needs Lesson 18's pumping lemma.
  5. Recovering structure or meaning from a string: the grammar, since it yields a parse tree.

The last line is why grammars dominate in practice. A machine answers yes or no; a grammar answers with a tree, and the tree is usually what the caller actually wanted.

117. Where this shows up: Context-Free Grammars

Real world

Discussion prompt

Outside this lesson: where does Context-Free Grammars actually turn up? Name one concrete situation — a job, a piece of software someone ships, a decision somebody has to make — and say which part of Choosing between a grammar and a machine is doing the work in it.

Hint: Vague is the failure mode here. "Engineering" is not a situation; "deciding whether this build is fast enough to ship" is.

Answer:

Lesson 13 introduces the first model that generates rather than recognizes. It covers variables, terminals, production rules, and the start variable, then one-step rewriting and why "context-free" means the surroundings are ignored, the language of a grammar, and the distinction between a sentential form and a member. It gives the four-tuple and the bar shorthand, then derivations, including the leftmost and rightmost disciplines and why they agree, and parse trees and yields with the many-derivations-one-tree relationship. A design recipe built on describing shapes recursively follows, with worked grammars for matched counts, palindromes, unions, and equal counts in any order. It closes by proving that every regular language is context-free via right-linear grammars, and showing that the containment is strict.

118. What comes next

Concept

Three questions are now open, and the next three lessons answer them in order.

  1. Some grammars give one string several trees. When does that matter, and can it be avoided? — Lesson 14.
  2. Grammars vary wildly in shape. Is there a normal form that makes proofs and algorithms uniform? — Lesson 15.
  3. What machine recognizes exactly this class? — Lesson 16.

After those, Lesson 17 proves the grammar and machine equivalent, Lesson 18 supplies the pumping lemma for this class, and Lesson 19 works out its closure properties — the same arc the regular chapters followed.

119. Break it if you can: What comes next

Counterexample

Discussion prompt

Three questions are now open, and the next three lessons answer them in order.

That is stated as though it always holds. Do one of two things: produce a case where it fails, or say precisely what rules such a case out. "It just does" is not on the menu.

Hint: Hunt at the extremes first — zero, one, negative, empty, equal. If every extreme survives, the reason they survive is the proof.

120. Connect it up: Context-Free Grammars

Connect it up

Draw it

One page, no notation unless you need it: draw how these connect — Generating Instead of Recognizing · The Formal Definition · Derivations · Parse Trees · Designing Grammars · Grammars and the Regular Languages. Put an arrow wherever one of them is what makes another possible, and label the arrow with why.

121. What you can do now

Recap

You can describe languages by generating them, and you have a class that finally handles nesting.

SituationMove
a language to describeask what a member looks like, one alternative per shape
two positions must be tiedput a variable between them
a union of two languagesfresh start variable, one alternative each
a derivation to recorddraw the parse tree, not the sequence
a regular language, needed as a grammarone variable per state, right-linear rules

Lesson 14 takes up the question this lesson opened: what it means for a grammar to give one string two structures, and what to do about it.

Sources

  1. Sipser, Introduction to the Theory of Computation, 3rd ed., Ch. 2.1 (Context-free grammars) — Cengage, 2013.
  2. Hopcroft, Motwani & Ullman, Introduction to Automata Theory, Languages, and Computation, 3rd ed., Ch. 5.1-5.2 (Context-free grammars and parse trees) — Pearson, 2007.
  3. Chomsky, 'Three models for the description of language', IRE Transactions on Information Theory 2(3) — IRE, 1956.
  4. Lewis & Papadimitriou, Elements of the Theory of Computation, 2nd ed., Ch. 3.1 (Context-free grammars) — Prentice Hall, 1998.
  5. Every derivation, parse tree and grammar in this deck was checked by hand against the strings claimed, including the empty-string boundary cases. — Verified 2026-08-08.

Want this taught 1-on-1? Alexander tutors Theory of Computation — $55/session, free consultation.

Book on Wyzant · Text (657) 465-8108