Question

I have the grammar:

S -> aSb | bSa | SS | epsilon

and I want to generate an unambiguous version.

I tried layering but only get to this, which is not unambiguous I don't believe, because the rules A -> aC and A -> AA are both possible for some inputs:

S -> A | epsilon

A -> aC | bD | AA

C -> Cb | b

D -> Da | a
Was it helpful?

Solution

S  -> aSb | bSa | SS | ϵ

If I’m not completely wrong here, the only issue here is the left recursion of S, so if you remove that, you should be fine:

S  -> S' S'
S' -> aSb | bSa | ϵ

This should also eliminate ambiguity.

An alternative solution could be this:

S  -> aSbS | bSaS | ϵ
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top