Difference between Left Factoring and Left Recursion

后端 未结 7 1162
长情又很酷
长情又很酷 2020-12-13 06:25

What is the difference between Left Factoring and Left Recursion ? I understand that Left factoring is a predictive top down parsing t

7条回答
  •  既然无缘
    2020-12-13 06:55

    left factor :

    Let the given grammar : A-->ab1 | ab2 | ab3

    1) we can see that, for every production, there is a common prefix & if we choose any production here, it is not confirmed that we will not need to backtrack.
    2) it is non deterministic, because we cannot choice any production and be assured that we will reach at our desired string by making the correct parse tree. but if we rewrite the grammar in a way that is deterministic and also leaves us flexible enough to convert it into any string that is possible without backtracking, it will be:

    A --> aA', A' --> b1 | b2| b3

    now if we are asked to make the parse tree for string ab2 and now we don't need back tracking. Because we can always choose the correct production when we get A' thus we will generate the correct parse tree.

    Left recursion :

    A --> Aa | b here it is clear that the left child of A will always be A if we choose the first production,this is left recursion .because , A is calling itself over and over again . the generated string from this grammar is : ba* since this cannot be in a grammar ... we eliminate the left recursion by writing :

    A --> bA' A' --> E | aA' now we will not have left recursion and also we can generate ba* .

提交回复
热议问题