How can I eliminate left recursion in the following grammar?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 12:28:13

问题


Here's the grammar, which is supposed to describe a language of nested braces with commas as delimiters:

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

A few more examples of strings I'd expect the grammar to accept and reject:

Accept:

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

Reject:

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

回答1:


Done by hand:

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

Or, instead of just winging it we could use a more systematic approach and apply the algorithm from Wikipedia on removing immediate left recursion:

L ::= { L } L1 | L1
L1 ::= ε | , L L1




回答2:


First of all, that grammar won't accept your first example, since it requires the commas to be after the close brace and before the open brace. I would suggest to re-write it as

L::= {L} | ,L

This won't get rid of the left recursion, but it will at least match your acceptable answers.



来源:https://stackoverflow.com/questions/1095774/how-can-i-eliminate-left-recursion-in-the-following-grammar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!