Context Free Grammar – What Makes a Context Free Grammar Ambiguous?

computer scienceformal-systems

What makes a context free grammar ambiguous?

Best Answer

A grammar is ambiguous if there's a word which has two different derivation trees. You'll have to look up derivation tree in your textbook since drawing them is awkward, but the idea that it doesn't matter in which order you're doing the derivations as long as it's basically the same derivation.

For example, consider the grammar \begin{align} S &\rightarrow AS|a \\ A &\rightarrow a \end{align}

Let's derive $aa$ twice: $$ S \rightarrow AS \rightarrow Aa \rightarrow aa $$ $$ S \rightarrow AS \rightarrow aS \rightarrow aa $$ These derivations share the same derivation tree:

Derivation tree

However, consider now the grammar \begin{align} S\rightarrow SS|a \end{align}

generating the same language.

There are now two "really" different derivations for $aaa$: $$S \rightarrow SS \rightarrow Sa \rightarrow SSa \rightarrow Saa \rightarrow aaa$$ $$S \rightarrow SS \rightarrow aS \rightarrow aSS \rightarrow aaS \rightarrow aaa$$

In the first derivation, the first two $a$'s are derived together, whereas in the second derivation, it is the second two $a$'s which are derived together. So it's $(aa)a$ vs. $a(aa)$.

First derivation tree

Second derivation tree

In this case, the language $a^+$ has an unambiguous grammar (the first one I exhibited), but in other cases, all grammars are ambiguous; such languages are called inherently ambiguous. See my other answer for more on that.

Related Question