Designing CFG's & PDA's
San Skulrattanakulchai
March 11, 2019
CFG Design
- CFG can be regarded as the method of defining strings recursively, which works as follow:
- [basis] give rules for the shortest strings in the language
- [recursion] give rules for constructing longer strings out of shorter ones
- For example, let’s try to get rules for the language of balanced parentheses (BP).
- The shortest string in BP is \(\varepsilon\), so this suggests the rule \(S\to\varepsilon\).
- Given a string in BP, one can get a longer one by adding
(
to its front and adding )
to its end. This suggests the rule \(S\to(S)\).
- Given two strings in BP, one can get a longer one by concatenating them. This suggests the rule \(S\to SS\).
- We now check that all strings in BP can be gotten this way. Consider any string \(w\) in BP. If \(|w| = 0\), then it can be obtained by Rule 1. So assume \(|w| > 0\). Note that \(w\) must start with
(
, otherwise it can’t be balanced. This initial (
has a unique matching )
. This matching closed paren is either at the last position of \(w\) or it is not. If it is, then removing the first and last character of \(w\) leaves a shorter string in BP. Thus \(w\) can be obtained by Rule 2. If it is not, then the prefix of \(w\) ending at this closing paren is in BP, and the remaining suffix of \(w\) is also in BP. Thus \(w\) can be obtained by Rule 3. Everything checks out.
PDA Design
- Here is one way:
- Break the task down into smaller steps.
- Write pseudocode for each step.
- Translate the pseudocode into PDA.
Example
Here is the pseudocode for \(\{ a^nb^n : n \ge 0 \}\).
while a do { read a & push a }
while b do { read b & pop a }
pop $
Here is the corresponding transition diagram.
Exercises
- For each language, give a CFG that generates it, or a PDA that recognizes it.
- palindromes over the alphabet \(\Sigma = \{a, b\}\)
- balanced parenthesis over \(\{ (, ) \}\)
- balanced parenthesis over \(\{ (, ), [, ] \}\)
- \(\{ a^{n+1} b^n : n\in\mathbb{N} \}\)
- \(\{ a^n b^{n+1} : n\in\mathbb{N} \}\)
- \(\{ a^m b^n : m < n \}\)
- \(\{ a^m b^n : m > n \}\)
- \(\{ a^m b^n : m \le n \}\)
- \(\{ a^m b^n : m \ge n \}\)
- \(\{ a^m b^n : m \ne n \}\)
- \(\{ a^{n+5} b^n : n\in\mathbb{N} \}\)
- \(\{ a^{2n} b^n : n\in\mathbb{N} \}\)
Exercises (continued)
- For each language, give a CFG that generates it, or a PDA that recognizes it.
- \(\{ a^{n+1} b^{2n} : n\in\mathbb{N} \}\)
- \(\{ a^m b^n : 2m = 3n \}\)
- \(\{ a^m b^n : m = 2n + 1 \}\)
- \(\{ a^m b^n : 2m \le n \le 3m \}\)
- \(\{ a^m b^n : m \ne 2n \}\)
- \(\{ a^n b c^n : n\in\mathbb{N} \}\)
- \(\{ a^m b^n c^n : m,n \in\mathbb{N} \}\)
- \(\{ a^m b^m c^n : m,n \in\mathbb{N} \}\)
- \(\{ a^m b^n c^m : m,n \in\mathbb{N} \}\)
- \(\{ a^k b^m c^n : n = m+k \}\)
- \(\{ a^k b^m c^n : n = k+2m \}\)
- \(\{ a^n ww^R b^n : w\in\Sigma^*, n \ge 1 \}\)