0

我有一个小问题。我需要做一个从自然数到其他自然数的谓词。我也必须进行检查,第二个间隔大于第一个。然而,我在路上被卡住了。

这是我的代码(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).但是我最后卡住了,它会导致堆栈溢出错误。

问题是如何让它停止?我几乎尝试了一切。=(

感谢您的答复!

4

3 回答 3

3

SWI-Prolog 有一个内置的...

?- help(between).
between(+Low, +High, ?Value)
    Low  and High are  integers, High >=Low.   If  Value is an  integer,
    Low=< Value=< High.   When Value  is a  variable it is  successively
    bound  to  all integers  between  Low and  High.    If High  is  inf
    or  infinite between/3 is  true iff Value>= Low,  a feature that  is
    particularly  interesting  for generating  integers from  a  certain
    value.

true.

?- between(1, 4, Value).
Value = 1 ;
Value = 2 ;
Value = 3 ;
Value = 4.

?- 
于 2010-10-19T13:48:18.847 回答
0

正如Paulo Moura所指出的,重新订购将解决部分问题。让它优雅地终止,可以通过添加一个附加子句来处理递归终止条件来实现。

尝试这个。

countAtoB(A,B,A) :-
    A =:= B, !.

countAtoB(A,B,A) :-
    A < B.

countAtoB(A,B,I) :- 
    A < B, 
    X is A+1,  
    countAtoB(X,B,I).

查询将如下所示。为了比较,我已经使用between/3重复了相同的一组测试查询,紧随其后。

?- countAtoB(1,4,I).
I = 1 ;
I = 2 ;
I = 3 ;
I = 4.

?- countAtoB(4,4,I).
I = 4.

?- countAtoB(4,1,I).
false.

?- countAtoB(4,1,1000).
false.

?- between(1,4,I).
I = 1 ;
I = 2 ;
I = 3 ;
I = 4.

?- between(4,4,I).
I = 4.

?- between(4,1,I).
false.

?- between(4,1,1000).
false.

?-
于 2014-02-06T23:47:51.567 回答
0

这个

count(A, B, C) :- count(A, B, D), ...

导致无限递归。

只需重新排序谓词,如下所示:

count(A, B, A) :- A =< B.
count(A, B, C) :- A < B, A2 is A+1, count(A2, B, C).
于 2010-10-19T12:50:49.343 回答