First time here? Checkout the FAQ!
0 votes
An unambiguous grammar has same leftmost and rightmost derivation

Please provide an example to show this.
asked in Compiler Design by Junior (621 points)   | 147 views

1 Answer

+1 vote

From Wikipedia:

An ambiguous grammar is a context-free grammar for which there exists a string that can have more than one leftmost derivation, while an unambiguous grammar is a context-free grammar for which every valid string has a unique leftmost derivation.

For a grammar to be unambiguous, they should generate same parse trees, which is only possible if there is unique LMD (and unique RMD) but it's not necessary for LMD and RMD to be same.

So your conclusion that LMD and RMD have to be same for a grammar to be unambiguous, is incorrect.

Consider the grammar:



Now string "aa" can have different LMD and RMD:

RMD: S→AS→Aa→aa

LMD: S→AS→aS→aa

But they generate the same parse tree (because the generation of any string has a unique LMD and a unique RMD). So the language is unambiguous.


Now consider the following grammar:


Now string "aaa" has two LMD derivations:

LMD1: S -> SS -> SSS -> aSS -> aaS -> aaa

LMD2: S -> SS -> aS -> aSS -> aaS -> aaa

So there will be two different parse trees, which you can confirm by drawing and hence the compiler will get confused which parse tree to follow in order to generate the string. So this grammar is ambiguous.

Notice that both grammars generate the same language.

answered by Loyal (3.3k points)  

Top Users Jun 2017
  1. Bikram

    3704 Points

  2. Hemant Parihar

    1502 Points

  3. junaid ahmad

    1432 Points

  4. Arnab Bhadra

    1416 Points

  5. Niraj Singh 2

    1391 Points

  6. Debashish Deka

    1246 Points

  7. Rupendra Choudhary

    1194 Points

  8. rahul sharma 5

    1158 Points

  9. Arjun

    956 Points

  10. srestha

    950 Points

Monthly Topper: Rs. 500 gift card
Top Users 2017 Jun 19 - 25
  1. Bikram

    1960 Points

  2. Niraj Singh 2

    1386 Points

  3. junaid ahmad

    502 Points

  4. Debashish Deka

    414 Points

  5. sudsho

    410 Points

23,373 questions
30,079 answers
28,396 users