序言统一解析

发布于 2024-08-06 19:32:19 字数 259 浏览 5 评论 0原文

为什么会这样:

   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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

江挽川 2024-08-13 19:32:19

因为算术运算只能通过 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.

岁月苍老的讽刺 2024-08-13 19:32:19

这两个定义都不能正常工作。

考虑

?- pow(1, 1, 2).

两个定义的循环,因为无论第二个参数如何,都可以应用第二个子句。第一个条款的删减无法撤销这一点。第二个子句需要一个目标 Y > 0 位于递归目标之前。使用 (is)/2 仍然是获得实际解决方案的好主意。

最好的(对于初学者)是从 并避免完全

请参阅例如: Prolog 谓词 - 无限循环

Both definitions do not work properly.

Consider

?- pow(1, 1, 2).

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 or and to avoid altogether.

See e.g.: Prolog predicate - infinite loop

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文