Sub topic 3
Context-free grammars: the four-tuple and basic examples
This chapter assumes you know what an alphabet, a string, and a language are. It also assumes you know finite automata and regular expressions, and can read set-builder notation such as { a^n b^n | n >= 1 }. Derivations, parse trees, and ambiguity come in the next chapters. Here we define the grammar itself and build a library of standard examples.
Why regular languages are not enough
A finite automaton has a fixed number of states, so it cannot count without bound. The language { a^n b^n | n >= 1 } needs the machine to remember how many a's it saw, and no finite automaton can do that. Balanced parentheses and nested expressions have the same problem.
A context-free grammar (CFG) fixes this by describing structure through recursion. A rule can mention the symbol it defines, so a string can be built from the outside in, with a matching pair of symbols added at each step.
The four-tuple
A CFG is a four-tuple G = (V, T, P, S).
| Component | Name | Meaning |
|---|---|---|
| V | Variables (non-terminals) | Symbols that stand for sets of strings. They are replaced during derivation. |
| T | Terminals | The alphabet of the language. They appear in the final strings. V and T are disjoint. |
| P | Productions | Rules of the form A -> α, where A is in V and α is a string over V ∪ T (possibly empty). |
| S | Start symbol | A variable in V from which every derivation begins. |
The language of G is the set of all terminal strings that can be derived from S:
L(G) = { w in T | S => w }
The symbol => means one derivation step. The symbol =>* means zero or more steps. A string that still contains variables is called a sentential form. A string made only of terminals is called a sentence.
The left side of every production is a single variable. This is what "context-free" means: a variable can be replaced no matter which symbols surround it. If a rule could look at the neighbours, as in aAb -> aab, the grammar would be context-sensitive.
Several productions with the same left side are written together with "|", so A -> α | β is shorthand for A -> α and A -> β. An empty right side is written ε.
First example: a^n b^n
Take L = { a^n b^n | n >= 1 } and the grammar
S -> a S b | a bHere V = {S}, T = {a, b}, and the start symbol is S. The rule S -> a S b wraps one a on the left and one b on the right. The rule S -> a b stops the recursion. Every use of the first rule adds one matched pair, so the numbers of a's and b's stay equal.
A derivation of aaabbb:
S => aSb => aaSbb => aaabbbThe first two steps use S -> a S b. The last step uses S -> a b. If the question allows n >= 0, replace the second rule with S -> ε.
Proving that a grammar generates a language
A grammar answers two questions, and a complete argument covers both.
- Soundness: every string the grammar derives is in the language. Here, induct on the number of derivation steps. Each use of
S -> a S bkeeps the counts of a and b equal. - Completeness: every string in the language can be derived. Here, induct on n. The string a^n b^n comes from S, then from a^(n-1) b^(n-1) wrapped in one a and one b.
In GATE you rarely write this proof. The habit still helps. Before choosing an option, test the grammar on the shortest strings of the language, then try to find one string outside the language that the grammar also derives.
A library of standard grammars
These patterns appear again and again in exam questions.
| Language | Grammar | Column | Column | Column | Column |
|---|---|---|---|---|---|
| { a^n b^n, n >= 0 } | S -> a S b \ | ε | |||
| { a^n b^(2n), n >= 0 } | S -> a S b b \ | ε | |||
| Palindromes over {a, b} | S -> a S a \ | b S b \ | a \ | b \ | ε |
| Even-length palindromes (w w^R) | S -> a S a \ | b S b \ | ε | ||
| Balanced parentheses | S -> ( S ) S \ | ε | |||
| { a^i b^j c^k, i = j or j = k } | Union of two grammars (see below) | ||||
| { a^i b^j, i ≠ j } | Split into i > j and i < j (see below) | ||||
| Strings with equal numbers of a and b | S -> a S b S \ | b S a S \ | ε |
Palindromes
A palindrome reads the same in both directions. Build it from the outside in: choose a matching pair of end symbols, then recurse on the middle. The middle of an odd-length palindrome is a single symbol, which is why a and b appear as base cases next to ε.
Balanced parentheses
The rule S -> ( S ) S | ε says that a balanced string is either empty or an opening parenthesis, a balanced string inside it, a closing parenthesis, and then another balanced string. The trailing S allows sequences such as ()(). A grammar with only S -> ( S ) would give nesting without concatenation.
Unions and concatenation
If L1 is generated by a grammar with start symbol S1 and L2 by one with start symbol S2, and the variable sets are disjoint, then:
- Union: add
S -> S1 | S2. - Concatenation: add
S -> S1 S2. - Kleene star of L1: add
S -> S1 S | ε.
This is the direct way to prove that CFLs are closed under union, concatenation, and star. Later chapters return to it.
Splitting a language into cases
Consider L = { a^i b^j c^k | i = j or j = k }. Write it as the union of L1 = { a^n b^n c^k } and L2 = { a^i b^n c^n }:
S -> S1 | S2
S1 -> X C
X -> a X b | ε
C -> c C | ε
S2 -> A Y
A -> a A | ε
Y -> b Y c | εFor { a^i b^j | i ≠ j }, split into i > j and i < j. For i > j, put at least one extra a in front of a balanced block:
S -> S1 | S2
S1 -> a S1 | a X
S2 -> S2 b | X b
X -> a X b | εThe comparison "not equal" cannot be checked directly. Turning it into "greater than or less than" makes both cases expressible with a balanced block plus a surplus.
Regular languages are context-free
Every regular language has a CFG. A grammar is right-linear if each production has the form A -> w B or A -> w, where w is a string of terminals. Such grammars generate exactly the regular languages. For a DFA, make one variable per state and add A -> a B for each transition from A to B on a. Then add A -> ε for each accepting state. So regular languages sit inside the context-free languages, and the inclusion is proper because a^n b^n is context-free but not regular.
Common mistakes
- Using the same variable in two separate grammars before combining them. Rename variables so the sets are disjoint.
- Forgetting the base case, so the grammar never produces a terminal string. Then L(G) is empty.
- Writing
S -> a S b b | εand claiming it generates a^n b^n. It generates a^n b^(2n). - Mixing up ε and the empty language. The grammar with L(G) = {ε} has the rule S -> ε. The empty language has no terminating derivation at all.
- Missing odd-length cases for palindromes.
Checking a grammar mechanically
A short script can enumerate strings up to a length bound and check a grammar against a membership test. This catches the mistakes above quickly.
from collections import deque
def generate(rules, start="S", max_len=6):
"""Return all terminal strings of length <= max_len derivable from start.
rules: dict mapping a variable (uppercase letter) to a list of right sides.
"""
seen = {start}
queue = deque([start])
result = set()
while queue:
form = queue.popleft()
idx = next((i for i, c in enumerate(form) if c.isupper()), None)
if idx is None:
result.add(form)
continue
for rhs in rules[form[idx]]:
new = form[:idx] + rhs + form[idx + 1:]
terminals = sum(1 for c in new if not c.isupper())
if terminals <= max_len and new not in seen:
seen.add(new)
queue.append(new)
return result
rules = {"S": ["aSb", "ab"]}
print(sorted(generate(rules, max_len=6), key=lambda s: (len(s), s)))
# ['ab', 'aabb', 'aaabbb']The search expands the leftmost variable each time. The length bound counts terminals only, so it terminates for grammars where every recursive rule adds a terminal. A grammar with a rule such as S -> S S or a rule that adds only variables can still loop through ever-longer forms, which is why this is a testing aid and not a decision procedure.
Exercises
Exercise
Write a CFG for L = { a^n b^m | m > n >= 0 }.
Show answer
S -> a S b | B, with B -> b B | b. Each use of the first rule adds a matching pair. The rule B generates at least one extra b, so m > n. For example, S => B => b is in L (n = 0, m = 1), and S => aSb => aBb => abbb is also in L (n = 1, m = 3).
Exercise
Which language does S -> a S a | b S b | ε generate, and what must you add to also get odd-length palindromes?
Show answer
It generates the even-length palindromes over {a, b}, that is { w w^R | w in {a, b}* }. Add the productions S -> a and S -> b (or S -> a | b) to allow a single middle symbol.
Exercise
Give a CFG for the set of strings over {a, b} with equal numbers of a's and b's, and show a derivation of abba.
Show answer
S -> a S b S | b S a S | ε. Derivation: S => a S b S => a b S a S b S ... is longer than needed, so use S => aSbS => a(bSaS)bS => abSaSbS and replace each remaining S by ε except the one that generates ba: S => a S b S, with the first S => b S a S => ba and the second S => ε, giving S => a(ba)b(ε) = abab. For abba use S => aSbS => a(bSaS)bS... Simpler: S => a S b S, take the first S => b S a S with both inner S => ε, which gives ab at that point wrapped as a(ba)b = abab. Since abba has the form b(ab)a... use S => b S a S with the first S => a S b S => ab and the second S => ε, giving S => bSaS => b(ab)a = baba. The string abba is obtained by S => aSbS with first S => ε and second S => b S a S: S => a S b S => a b S => a b b S a S => abba.