Sub topic 3
Context-Free Grammars: The Four-Tuple and Basic Examples
Assume you know alphabets, strings, languages, finite automata, and basic set notation. A context-free grammar (CFG) gives a finite description of some languages that finite automata cannot recognise, such as strings with equal numbers of a symbols followed by b symbols.
The four-tuple
A CFG is a four-tuple:
\[ G = (V, \Sigma, P, S) \]
Each component has a specific role.
| Component | Meaning | Example |
|---|---|---|
| \(V\) | A finite set of variables, also called nonterminals | \(\{S\}\) |
| \(\Sigma\) | A finite set of terminals | \(\{a,b\}\) |
| \(P\) | A finite set of production rules | \(S \to aSb \mid ab\) |
| \(S\) | The start variable | \(S\) |
Terminals are symbols that appear in completed strings. Variables are temporary symbols used while generating a string. A production replaces one variable with a sequence of terminals and variables.
The language generated by \(G\), written \(L(G)\), contains exactly the terminal-only strings that can be produced from the start variable.
A production such as
\[ S \to aSb \]
means that an occurrence of \(S\) may be replaced by aSb. The notation
\[ S \to aSb \mid ab \]
is shorthand for two productions:
- \(S \to aSb\)
- \(S \to ab\)
Example: matching numbers of symbols
Consider:
Language: L = { a^n b^n | n >= 1 }
Grammar:
S -> a S b
S -> a bThe second rule is the base case. It produces one a and one b. The first rule adds one a to the left and one b to the right. Therefore, the grammar generates:
abaabbaaabbbaaaabbbb
It does not generate aab, abb, or abab. The grammar enforces both the order of the symbols and equality of their counts.
Example: balanced parentheses
The grammar below generates balanced parentheses:
S -> (S)S
S -> εHere, \(\varepsilon\) is the empty string. The rule \(S \to \varepsilon\) stops the recursive expansion. For example, choosing \(S \to (S)S\), then replacing both remaining variables by \(\varepsilon\), produces ().
The recursive structure ensures that every opening parenthesis has a matching closing parenthesis. It can also generate ()(), (()), and (()()).
A useful mental model
A CFG describes nested structure. A finite automaton has only finitely many states, so it cannot remember an unbounded number of earlier symbols. A CFG uses recursive variables to represent that unbounded structure. A pushdown automaton provides the corresponding machine model with a stack.
Exercise
What language is generated by the grammar S -> aS | b, and what is its shortest string?
Show answer
It generates {a^k b | k >= 0}. The shortest string is b.