1

我有这个语法

S->S+S|SS|(S)|S*|a

我想知道如何从这个语法中消除左递归,因为这S+S真的很令人困惑......

4

2 回答 2

2

让我们看看我们是否可以简化给定的语法。

S -> S*|S+S|SS|(S)|a

我们可以写成;

S -> S*|SQ|SS|B|a
Q -> +S
B -> (S)

现在,您可以在熟悉的领域消除左递归。

S  ->  BS'|aS'
S' ->  *S'|QS'|SS'|e
Q  ->  +S
B  ->  (S)

请注意,e 是 epsilon/lambda。

我们已经移除了左递归,所以我们不再需要 Q 和 B。

S  ->  (S)S'|aS'
S' ->  *S'|+SS'|SS'|e

在处理左递归消除时,您会发现这很有用

于 2012-12-25T19:46:35.113 回答
0

My answer using theory from this reference

How to Eliminate Left recursion in Context-Free-Grammar.

S -->  S+S | SS | S*    |        a | (S)
      --------------            -------   
      Sα form                   β form    
      Left-Recursive-Rules      Non-Left-Recursive-Rules       

We can write like

S ---> Sα1 | Sα2 | Sα3 | β1 | β2

Rules to convert in equivalent Non-recursive grammar:

S ---> β1 | β2
Z ---> α1 | α2 | α3
Z ---> α1Z | α2Z | α3Z
S ---> β1Z | β2Z

Where

α1 = +S
α2 = S
α3 = *

And β-productions not start starts with S:

β1 = a
β2 = (S)

Grammar without left-recursion:

Non- left recursive Productions S --> βn

S -->  a | (S)   

Introduce new variable Z with following productions: Z ---> αn and Z --> αnZ

Z --> +S | S | * 

and 

Z --> +SZ | SZ | *Z  

And new S productions: S --> βnZ

S -->  aZ | (S)Z     

Second form (answer)

Productions Z --> +S | S | * and Z --> +SZ | SZ | *Z can be combine as Z --> +SZ | SZ | *Z| ^ where ^ is null-symbol.

Z --> ^ use to remove Z from production rules.

So second answer:

S --> aZ | (S)Z and Z --> +SZ | SZ | *Z| ^

于 2012-12-26T13:13:09.457 回答