Prolog中的递归问题-在退出递归时得到False而不是True



我正在Prolog中尝试执行一个简单的程序,该程序将决定谓词是True还是False。基本上我解决了这个问题,但我发现一个输入不起作用。我知道为什么,但我不知道如何解决它。

谓词的形式如下:

getPred(L, A, B, Y)
L - is a list containing intv predicates - intv(K,L,V) - < K,L > is interval and V is any value
< A,B > - is an interval
Y - value

任务是:

If < K,L > is in < A,B > add V to a sum. If it does not belong to < A,B >, ignore it.  
Finally, compare the sum of correct V values with Y. If it is equal - True, otherwise False. 

以下是正确的TRUE谓词示例:

getPred([intv(2,10,15),intv(5,8,23), intv(12,15,8), intv(14,17,13)], 3, 16, 31).
getPred([intv(2,10,15),intv(5,8,23), intv(12,15,8), intv(14,17,13)], 3, 20, 44).

我的代码是:

getPred(List, A, B, Y) :-
S is 0,
program(List, A, B, Y, S).
program([], _, _, Y, S) :-
S =:= Y.
program([intv(K,L,V)|P], A, B, Y, S) :-
isinINTV(K, L, V, A, B, P, Y, S).
isinINTV(K, L, V, A, B, P, Y, S) :-
K >= A,
L =< B,
S2 = S+V,
program(P,A,B,Y,S2).
isinINTV(K, L, V, A, B, P, Y, S) :-
program(P,A,B,Y,S).

除非我尝试了这个谓词,否则我的程序运行得很好getPred([intv(2,10,10(,intv(5,8,10(],1,20,10(。

问题是当Y!=S、 递归正在返回并再次询问相同的条件,但后来Y==S,因为返回递归意味着S中有一个旧值。

谢谢你的帮助。重要的是:我不想使用任何内置谓词。

尝试:

check(Intervals, Inf, Sup, Value) :-
check(Intervals, Inf, Sup, 0, Sum),
Sum =:= Value.
check([], _, _, Sum, Sum).
check([intv(Inf0,Sup0,Value)| Intvs], Inf, Sup, Sum0, Sum) :-
(   Inf0 >= Inf,
Sup0 =< Sup ->
Sum1 is Sum0 + Value,
check(Intvs, Inf, Sup, Sum1, Sum)
;   check(Intvs, Inf, Sup, Sum0, Sum)
).

为了更容易阅读代码,进行了一些重命名。示例调用:

| ?- check([intv(2,10,15),intv(5,8,23), intv(12,15,8), intv(14,17,13)], 3, 16, 31).
yes
| ?- check([intv(2,10,15),intv(5,8,23), intv(12,15,8), intv(14,17,13)], 3, 20, 44).
yes
| ?- check([intv(2,10,10),intv(5,8,10)], 1, 20, 10).
no

请注意,此解决方案还避免了原始代码中的虚假选择点。

最新更新