-1

An ambiguous grammar is given and I am asked to rewrite the grammar to make it unambiguous. In fact, I don't know why the given grammar is ambiguous, let alone rewriting it to an unambiguous one.

The given grammar is S -> SS | a | b , and I have four choices:

A: S -> Sa | Sb | epsilon  

B: S -> SS’
   S’-> a | b  

C: S -> S | S’
   S’-> a | b 

D: S -> Sa | Sb. 

For each choice, I have already know that D is incorrect because it generates no strings at all,C is incorrect because it only matches the strings 'a' and 'b'.

However, I think the answer is A while the correct answer is B.I think B is wrong because it just generates S over and over again, and B can't deal with empty strings.

  1. Why is the given grammar ambiguous?

  2. Why is A incorrect while B is correct?

Zhao
  • 119
  • 1
  • 9

1 Answers1

0

The original grammar is ambiguous because multiple right-most (or left-most) derivations are possible for any string of at least three letters. For example:

S -> SS -> SSS -> SSa -> Saa -> aaa
S -> SS -> Sa  -> SSa -> Saa -> aaa

The first one corresponds, roughly speaking, to the parse a(aa) while the second to the parse (aa)a.

None of the alternatives is correct. A incorrectly matches ε while B does not match anything (like D). If B were, for example,

S  -> SS' | S'
S' -> a | b

it would be correct. (This grammar is left-associative.)

rici
  • 234,347
  • 28
  • 237
  • 341