Prolog 中的数字递增
我正在尝试在序言中实现增量,并编写了以下代码:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这两个程序都不起作用,因为它们包含无限递归。您可以在自身内部调用
coordenate
,而无需停止条件。然后,为了帮助您解决就地递增变量的原始问题:您无法在 Prolog 中执行此操作。一旦变量被绑定,您就无法更改其绑定。在 Prolog 中编程时,您必须考虑关系和递归,而不是可变状态。以下是在 Prolog 中递增的方法:
请注意,需要两个变量:一个用于保存原始值,另一个用于保存递增后的值。要对该谓词执行的计算执行任何有用的操作,两个变量都必须是谓词的参数。第一个作为输入参数,第二个作为输出参数(尽管这没有反映在语言中,但它遵循
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:
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).