序言统一解析
为什么会这样:
power(_,0,1) :- !.
power(X,Y,Z) :-
Y1 is Y - 1,
power(X,Y1,Z1),
Z is X * Z1.
这会导致堆栈溢出异常吗?
power(_,0,1) :- !.
power(X,Y,Z) :-
power(X,Y - 1,Z1),
Z is X * Z1.
Why does this work:
power(_,0,1) :- !.
power(X,Y,Z) :-
Y1 is Y - 1,
power(X,Y1,Z1),
Z is X * Z1.
And this gives a stack overflow exception?
power(_,0,1) :- !.
power(X,Y,Z) :-
power(X,Y - 1,Z1),
Z is X * Z1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为算术运算只能通过 is 运算符对子句进行。在第一个示例中,Y1 绑定到计算 Y - 1 的结果。在后面,系统尝试证明子句 power(X, Y - 1, Z1),它与 power(X', Y', Z') 绑定 X' = X, Y' = Y - 1, Z' = Z。然后再次递归,因此 Y'' = Y - 1 - 1 等无穷大,从未实际执行计算。
Prolog 主要只是术语的统一——在“普通”意义上的计算,必须明确要求。
Because arithmetic operations are only performed on clauses through the
is
operator. In your first example, Y1 is bound to the result of calculating Y - 1. In the later, the system attempts to prove the clause power(X, Y - 1, Z1), which unifies with power(X', Y', Z') binding X' = X, Y' = Y - 1, Z' = Z. This then recurses again, so Y'' = Y - 1 - 1, etc for infinity, never actually performing the calculation.Prolog is primarily just unification of terms - calculation, in the "common" sense, has to be asked for explicitly.
这两个定义都不能正常工作。
考虑
两个定义的循环,因为无论第二个参数如何,都可以应用第二个子句。第一个条款的删减无法撤销这一点。第二个子句需要一个目标
Y > 0
位于递归目标之前。使用(is)/2
仍然是获得实际解决方案的好主意。最好的(对于初学者)是从 successor 开始-arithmetics 或 clpfd 并避免完全prolog-cut。
请参阅例如: Prolog 谓词 - 无限循环
Both definitions do not work properly.
Consider
which loops for both definitions because the second clause can be applied regardless of the second argument. The cut in the first clause cannot undo this. The second clause needs a goal
Y > 0
before the recursive goal. Using(is)/2
is still a good idea to get actual solutions.The best (for beginners) is to start with successor-arithmetics or clpfd and to avoid prolog-cut altogether.
See e.g.: Prolog predicate - infinite loop