0

I've been given a homework task to convert the following grammar to unambiguous.

A --> B
A --> ε
B --> B @ B
B --> STRING
B --> DOUBLE(STRING)

where A and B are non-terminals and STRING and DOUBLE are non-terminals.

I can derive that it is ambiguous given two different parse trees can be constructed for a string such as :

STRING @ STRING @ DOUBLE(STRING).

So far, I've got:

A --> B | ε
B --> B @ DOUBLE(STRING)
B --> C
C --> C @ STRING | STRING | DOUBLE(STRING)

however it's not complete as the string such as:

STRING @ DOUBLE(STRING) @ STRING

cannot be made. How would I convert this grammar to unambiguous?

Neri Villa
  • 35
  • 6

2 Answers2

0
STRING @ STRING @ STRING

could result from A ⇒ B @(B @ B) or A ⇒ (B @ B) @ B because of

B --> B @ B

The solution is to introduce a new B-alike non-terminal and replace on of the occurrences with that nonterminal. This introduces an assymetry, you will find in many grammars.

The pleasure to figure out the rest I leave to you.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Thanks Joop. I've edited my post to what I think is what I could do best however I feel like my implementation of asymmetry is incorrect. – Neri Villa Oct 05 '18 at 09:17
  • You have to mentally work out such a grammar yourself, as grammars are hard in the beginning. `B --> X (@ Y)*` would be more like the final desired result. Maybe drawing parse trees helps. – Joop Eggen Oct 05 '18 at 09:36
  • Sorry this whole concept of CFG is new to me but what does ' * ' mean and how would you apply that into a CFG? – Neri Villa Oct 05 '18 at 12:38
  • That was intended as pseudo-code. The postfix operator ` *` means 0 or more repetitions of the prior expression. Maybe you know the same thing as ` { @ Y }`. `B -> C | B | @ C` . would be an unambiguous repetition. – Joop Eggen Oct 06 '18 at 14:17
0

Continuing Joop's answer, you can introduce a new symbol D to eliminate the ambiguity around B --> B @ B:

A --> D
A --> ε
D --> D @ B
D --> B
B --> STRING
B --> DOUBLE(STRING)

With this change, only one tree is possible for any string in the language.

Patrick87
  • 27,682
  • 3
  • 38
  • 73