This is an old revision of the document!


9. Context-Free Languages

Write a PDA as well as a CF grammar for the following languages. Specify - for each PDA, the way it accepts (by empty-stack or by final state). For each grammar, make sure it is not ambiguous. (Start with any CF grammar that accepts L. Then write another non-ambiguous grammar for the same language).

9.1.1. $ L = \{\: w \in \{A,B\}^* \ | \:w \text{ is a palindrome}\} $.

9.1.2. $ L = \{ A^{m} B^{m+n} C^{n} \ | \: n, m \geq 0 \} $

9.1.3. $ L = \{w \in \{a, b\}^* | \#_a(w) = \#_b(w) \} $

Click to display ⇲

Click to hide ⇱

Try #1:
$ S \leftarrow aBS | baS | \epsilon $
incomplete because of: “aabb”
Try #2:
$ S \leftarrow $ aSb | bSa | SS | $ \epsilon $
incomplete because of: “abab”
Idea: A = rule that promises that exactly one letter 'a' is extra; B = rule that promises that exactly one letter 'b' is extra
$ S \leftarrow aBS | bAS | \epsilon $
$ A \leftarrow a | bAA $
$ B \leftarrow b | aBB $

We can easily check by induction (over the length of the derivation sequence) that $ A \Rightarrow^* w$ iff $ \#_A(w) = 1 + \#_B(w)$ . The basis case (length 1) is straightforward as $ A \Rightarrow a$ . Now suppose $ A \Rightarrow bAA \Rightarrow^* bw_1w_2$ . By induction hypothesis: $ \#_A(bw_1w_2) = \#_A(w_1) + \#_A(w_2) = \#_B(w_1) + 1 + \#_B(w_2) + 1 = \#_B(bw_1w_2)+1$ .

9.1.4. $ L = \{w \in \{a, b\}^* | \#_a(w) \neq \#_b(w) \} $

9.1.5. $ L = \{a^ib^jc^k | i = j \lor j = k \} $

Which of the following grammars are ambiguous? Justify each answer. Modify the grammar to remove ambiguity, wherever the case.

9.2.1.

$ S \leftarrow aA | A $
$ A \leftarrow aA | B $
$ B \leftarrow bB | \epsilon $

9.2.2.

$ S \leftarrow AS | \epsilon $
$ A \leftarrow 0A1 | 01 | B $
$ B \leftarrow B1 | \epsilon $

9.2.3.

$ S \leftarrow ASB | BSA | \epsilon $
$ A \leftarrow aA | \epsilon $
$ B \leftarrow bB | \epsilon $

9.2.4. Write an ambiguous grammar for $ L(a^*) $.