Prolog 中的数字递增

发布于 2024-12-17 02:07:08 字数 411 浏览 5 评论 0原文

我正在尝试在序言中实现增量,并编写了以下代码:

coordinate(X,Y,Z):- 
           X is 1, 
           Y is 1,
           Z is 1, 
           coordinate(X1,Y1,Z1), 
           X1 is X+1, 
           Y1 is Y+1, 
           Z1 is Z.

我也尝试过:

coordinate(X,Y,Z):-
          X is 1,
          Y is 1,
          Z is 1,
          coordinate(X+1,Y+1,X+1).

这些都不起作用。谁能解释为什么?

I'm trying to implement an increment in prolog, and have written the following code:

coordinate(X,Y,Z):- 
           X is 1, 
           Y is 1,
           Z is 1, 
           coordinate(X1,Y1,Z1), 
           X1 is X+1, 
           Y1 is Y+1, 
           Z1 is Z.

I also tried:

coordinate(X,Y,Z):-
          X is 1,
          Y is 1,
          Z is 1,
          coordinate(X+1,Y+1,X+1).

Neither of these work. Can anyone explain why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

残疾 2024-12-24 02:07:08

这两个程序都不起作用,因为它们包含无限递归。您可以在自身内部调用coordenate,而无需停止条件。

然后,为了帮助您解决就地递增变量的原始问题:您无法在 Prolog 中执行此操作。一旦变量被绑定,您就无法更改其绑定。在 Prolog 中编程时,您必须考虑关系和递归,而不是可变状态。以下是在 Prolog 中递增的方法:

incr(X, X1) :-
    X1 is X+1.

请注意,需要两个变量:一个用于保存原始值,另一个用于保存递增后的值。要对该谓词执行的计算执行任何有用的操作,两个变量都必须是谓词的参数。第一个作为输入参数,第二个作为输出参数(尽管这没有反映在语言中,但它遵循 is/2 的工作方式)。

Neither program works because they contain infinite recursion. You call coordenate within itself, without a stopping condition.

Then, to help you with your original problem of incrementing a variable in-place: you can't do that in Prolog. Once a variable is bound, you can't change its binding. When programming in Prolog, you have to think in terms of relations and recursion, not mutable state. Here's how to increment in Prolog:

incr(X, X1) :-
    X1 is X+1.

Note that two variables are needed: one to hold the original value and one for the incremented value. To do anything useful with the computation that this predicate performs, both variables have to be arguments of the predicate. The first is meant as an input argument, the second as an output argument (though this isn't reflected in the language, it follows from the way is/2 works).

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