Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在DCG-Prolog中消除左递归_Prolog_Grammar_Dcg_Left Recursion_Prolog Tabling - Fatal编程技术网

在DCG-Prolog中消除左递归

在DCG-Prolog中消除左递归,prolog,grammar,dcg,left-recursion,prolog-tabling,Prolog,Grammar,Dcg,Left Recursion,Prolog Tabling,这个语法中的左递归有一个小问题。我试图用Prolog编写它,但我不知道如何删除左递归 <expression> -> <simple_expression> <simple_expression> -> <simple_expression> <binary_operator> <simple_expression> <simple_expression> -> <function>

这个语法中的左递归有一个小问题。我试图用Prolog编写它,但我不知道如何删除左递归

<expression> -> <simple_expression>
<simple_expression> -> <simple_expression> <binary_operator> <simple_expression>
<simple_expression> -> <function>
<function> -> <function> <atom>
<function> -> <atom>
<atom> -> <number> | <variable>

<binary_operator> -> + | - | * | /

expression(Expr) --> simple_expression(SExpr), { Expr = SExpr }.
simple_expression(SExpr) --> simple_expression(SExpr1), binary_operator(Op), simple_expression(SExpr2), { SExpr =.. [Op, SExpr1, SExpr2] }.
simple_expression(SExpr) --> function(Func), { SExpr = Func }.
function(Func) --> function(Func2), atom(At), { Func = [Func2, atom(At)] }.
function(Func) --> atom(At), { Func = At }.
->
->   
-> 
->  
-> 
->  | 
-> + | - | * | /
表达式(Expr)-->简单表达式(SExpr),{Expr=SExpr}。
简单表达式(SExpr)-->简单表达式(SExpr1),二进制运算符(Op),简单表达式(SExpr2),{SExpr=..[Op,SExpr1,SExpr2]}。
简单表达式(SExpr)-->函数(Func),{SExpr=Func}。
函数(Func)->函数(Func2),原子(At),{Func=[Func2,原子(At)]}。
函数(Func)-->atom(At),{Func=At}。

我写过类似的东西,但根本没用。如何更改它以使该程序工作?

程序的问题确实是左递归;它应该被移除,否则你会陷入无限循环

若要删除立即左递归,请替换表单的每个规则

A->a1 | a2 | b1 | b2

与:

所以函数是

function -> atom, functionR.
funtionR -> [].

来自@thanosQR的答案相当不错,但适用于比DCG更一般的上下文,并且需要更改解析树。实际上,解析的“结果”已被删除,这并不好

如果你对解析表达式感兴趣,我发布了一些有用的东西

答案集编程(ASP)提供了另一种实现语法的途径。 ASP可以通过非确定性正向链接实现,这就是 我们的库(minimal/asp)提供。ASP的结果是不同的模型

对给定规则的修改。在这里,我们使用ASP模型来表示Cocke Yourger Kasami 图表。我们以给定的要解析的单词开始图表,这些单词是 由word/3事实表示。与DCG相比,我们不再传递信息

只列出单词的位置。Prolog文本显示了这样一个实现 一个基于ASP的解析器。现在所有的规则都被取消了(
function -> atom, functionR.
funtionR -> [].
choose([expr(C, I, O)]) <= posted(expr(A, I, H)), word('+', H, J), term(B, J, O),  C is A+B.
choose([expr(C, I, O)]) <= posted(expr(A, I, H)), word('-', H, J), term(B, J, O),  C is A-B.
choose([expr(B, I, O)]) <= posted(word('-', I, H)), term(A, H, O), B is -A.
choose([expr(A, I, O)]) <= posted(term(A, I, O)).
?- post(word(78,7,8)), post(word('+',6,7)), post(word(56,5,6)), post(word('*',4,5)),
    post(word(34,3,4)), post(word('+',2,3)), post(word(12,1,2)), post(word('-',0,1)),
    expr(X,0,8).
X = 1970