How can I eliminate left recursion in the following grammar?

Here's a grammar that should describe the language of enclosed braces with commas as separators:

L ::= {L} | L,L | 

A few examples of lines that I would expect the grammar to accept and reject:

Accept:

 {,{,,{,}},,{,}} {{{{}}}} {,{}} 

Reject

 {}{} {,{}{}} {{},{} 
+2
source share
2 answers

Manually done:

L :: = { L } | { L } , | , L | & Epsilon;

Or instead of just using wings, we could use a more systematic approach and apply the algorithm from Wikipedia to remove the immediate left recursion :

L :: = { L } L 1 | L <sub> 1sub>
L 1 :: =? | , LL 1

+4
source

First of all, this grammar will not take your first example, since it requires the commas to be after the closing bracket and before the open curly bracket. I would suggest rewriting it as

 L::= {L} | ,L 

This will not save you from left recursion, but at least will match your acceptable answers.

0
source

Source: https://habr.com/ru/post/1446984/


All Articles