-1

I have the following problem. This grammar is ambiguous:

stmt -> if expr then stmt stmt’ | a

stmt’ -> else stmt | EPSILON

expr -> b

I tried to modify it and my result is:

stmt -> if expr then stmt’’ | a

stmt’’ -> stmt | stmt’

stmt’ -> B else stmt

expr -> b

But this does not generate the same language.

Can somebody help me modify the ambiguous grammar so that it is unambiguous and accepts the same language?

Community
  • 1
  • 1

1 Answers1

2

Using the given grammar, there are two left most derivations for the string if b then if b then a else a as follows.

Derivation 1:

if expr then stmt stmt'
if b then stmt stmt'
if b then if expr then stmt stmt' stmt'
if b then if b then stmt stmt' stmt'
if b then if b then a stmt' stmt'
if b then if b then a stmt'
if b then if b then a else stmt
if b then if b then a else a

Derivation 2:

if expr then stmt stmt'
if b then stmt stmt'
if b then if expr then stmt stmt' stmt'
if b then if b then stmt stmt' stmt'
if b then if b then a stmt' stmt'
if b then if b then a else stmt stmt'
if b then if b then a else a stmt'
if b then if b then a else a

The parse trees remains same for most part. But after deriving if b then if b then a stmt' stmt', the order of nodes changes thus affecting the structure of the tree. Hence the given grammar is ambiguous.

Pratap
  • 402
  • 2
  • 6
  • Though upvoted,but, OP asked for removing ambiguity of the grammar. I had a tough time even proving ambiguity. Thanks for brilliant effort. – Am_I_Helpful Jun 09 '15 at 06:06