Prolog,从一个区间开始计数; (SWI-PROLOG)
我有一个小问题。我需要创建一个从自然数到其他自然数的谓词。我也必须进行检查,确保第二个间隔大于第一个间隔。然而我在路上被困住了。
这是我的代码(SWI-PROLOG)
count(O, _, O).
count(A, B, C) :- count(A, B, D), C is D+1, C =< B.
它工作得很好,如果我输入 我可以获得结果
但是我在最后卡住了,这会导致堆栈溢出错误。C=1, C=2, C=3, C=4
count(1, 4, C).
问题是我该如何让它停下来?我几乎尝试了一切。 =(
谢谢您的回复!
I have a small question. I need to make a predicate that counts from a natural number to some other natural number. I have to implement a check too, that the second interval is bigger than the first one. However I got stuck during my way.
Here is my code (SWI-PROLOG)
count(O, _, O).
count(A, B, C) :- count(A, B, D), C is D+1, C =< B.
It works kind of well as, I can get the results C=1, C=2, C=3, C=4
if I type in count(1, 4, C).
However I get stuck at the end, it will result in an error with stack overflow.
The question is how do I make it to stop? I have tried almost everything. =(
Thanks for your response!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SWI-Prolog 有一个内置功能...
SWI-Prolog has a builtin for that...
正如 Paulo Moura 指出的那样,重新排序将解决部分问题。让它优雅地终止,可以通过添加一个附加子句来处理递归终止条件来实现。
试试这个。
查询将如下所示。为了进行比较,我使用 Between/3 重复了同一组测试查询,之后海峡。
As Paulo Moura pointed out, re-ordering will solve part of the problem. Getting it to terminate gracefully, may be achieved by adding an additional clause to handle the recursive terminating condition.
Try this.
Queries would then look like this. For the sake of comparison, I have repeated the same set of test queries using between/3, strait after.
这
会导致无限递归。
只需重新排序谓词,如下所示:
This
causes an infinite recursion.
Just reorder the predicate, like this: