CSCI 301 L28 Worksheet

Lecture 28 - Exercises

Grammar 1: \(\Sigma = \{a, b\}, V = \{S\}, S = S\) \[ \begin{align*} S &\rightarrow \epsilon\\ S &\rightarrow aSa\\ S &\rightarrow bSb \end{align*} \]

Grammar 2: \(\Sigma = \{a, b\}, V = \{S\}, S = S\) \[ \begin{align*} S &\rightarrow \epsilon\\ S &\rightarrow aSbS\\ S &\rightarrow bSaS\\ \end{align*} \]

Part A - Leftmost, Rightmost Derivations; Ambiguous Grammars

  1. Give a leftmost derivation of \(abab\) in Grammar 2 above.
  2. Give a rightmost derivation of \(abab\) in Grammar 2 above.
  3. Are their parse trees the same?
  4. Show that Grammar 2 above is ambiguous by finding more than one left-most derivation for the string \(abaabb\).

Part B - Parsing and Left Recursion

  1. Consider the grammar \(S \rightarrow aS \mid bS \mid \epsilon\). Find a derivation for the string \(aabb\). At each step, how many characters of the input string did you need to look at to know which rule to apply?
  2. Repeat the same exercise for the grammar \(S \rightarrow Sa \mid Sb \mid \epsilon\).

Part C - Eliminating Left Recursion

  1. Rewrite the following grammar to eliminate left recursion:

    \[S \rightarrow Sa \mid Sb \mid AB \mid C \mid \epsilon\]

  2. Rewrite the following grammar to eliminate left recursion (note that \(\_\), digits \(0-9\), and \(+, -, *\) and \(/\) are terminals in this grammar): \[ \begin{align*} S &\rightarrow \_ S \mid SP \mid NS \mid E\\ N &\rightarrow ND \mid D\\ D &\rightarrow 0 \mid 1 \mid \cdots \mid 9\\ P &\rightarrow + \mid - \mid * \mid / \end{align*} \]

Part D - Left Factoring (Eliminating Common Prefixes)

Consider the following grammar, in which \(+\), \(*\), and \(a\) are terminals: \[ S \rightarrow S S + \mid SS * \mid a \]

\[ \begin{align*} E &\rightarrow E + T \mid T\\ T &\rightarrow T F \mid F\\ F &\rightarrow F * \mid P\\ P &\rightarrow a \mid b \end{align*} \]

  1. Left factor the grammar, rewriting an equivalent grammar such that no rules have a common prefix.