提供结果后,Prolog卡住

时间:2019-05-17 19:41:48

标签: prolog failure-slice

所以我有这个知识库,我正在努力实现注释中给出的代码目标。

%format of foo: foo(Tag,NumList) 
foo(a, [2, 4]). 
foo(b,[2, 8, 8, 6,2]). 
foo(c,[4, 8, 8, 8, 7]). 
foo(d,[7, 8, 8, 2]). 
foo(e,[5, 8, 9, 6]).
foo(f,[2, 5]). 
foo(g,[2, 6]). 
foo(h, [2, 8, 2]). 
foo(i, [2, 8, 8, 2]).
foo(j, [2, 3]).

但是粘胶部分有问题。当我只将Total_num分配给goo并获得Foo_list的统一结果时,它给出了结果,但是之后就被卡住了。什么都没用,我必须一直关闭翻译。

我尝试过削减好帮手,但没有任何效果。另外,当我更改goo中的谓词顺序(将goo_ordered放在前面)时,它不会给出列表,只会卡住。我该如何解决这个问题?是什么原因造成的?

谢谢

%returns the sum of the numbers the NumList
foo_sum(Tag,SUM):- foo(Tag,List),foo_sum_helper(List,SUM).

foo_sum_helper([],0).
foo_sum_helper([H|T],Result):- foo_sum_helper(T,Prev_result), Result is H + Prev_result.

%foo diff find the last number in the list.
%It should remain the if it is less than or equal to four, otherwise substract 8 from it
foo_diff(Tag,Diff):- foo(Tag,List),foo_diff_helper(List,Diff).

foo_diff_helper([Last],Result):- Last =< 4, Result is Last,!.
foo_diff_helper([Last],Result):- Last > 4, Result is Last - 4,!.
foo_diff_helper([_,X|T],Result):- foo_diff_helper([X|T], Result).

%goo takes a list of foo's and a number that represents the total number of each foo_sum of foo's.
%Total of foo_diff must be 0
%Also the list of foo's must be in the ascending order.(foo_sum of the first foo in the list is the least one.)

goo(Foo_list,Total_num):- goo_sum(Foo_List,Total_num),goo_diff(Foo_list,0),goo_ordered(Foo_list).

goo_ordered([]).
goo_ordered([_]).
goo_ordered([X,Y|Z]):- foo_sum(X,NUMX),foo_sum(Y,NUMY),NUMX =< NUMY, goo_ordered([Y|Z]).

goo_sum([X],RESULT):- foo_sum(X,RESULT).
goo_sum([H|T],RESULT):- goo_sum(T,PREV_RESULT),foo_sum(H,NUMH), RESULT is NUMH + PREV_RESULT.

goo_diff([X],RESULT):- foo_diff(X,RESULT).
goo_diff([H|T],RESULT):- goo_diff(T,PREV_RESULT),foo_diff(H,HDIFF), RESULT is HDIFF + PREV_RESULT.

1 个答案:

答案 0 :(得分:2)

  

是什么原因造成的?

假设您的意思是循环goo_sum(X, 20)

对于查询,我得到了很多答案。其实对我来说太多了。所以我会考虑

?- goo_sum(X, 20), false.

循环。 一个原因是以下非常紧凑的

goo_sum([X],RESULT):- false, foo_sum(X,RESULT).
goo_sum([H|T],RESULT):-
   goo_sum(T,PREV_RESULT), false,
   foo_sum(H,NUMH), RESULT is NUMH + PREV_RESULT.

您需要以某种方式修复其余部分,否则循环将保留。

顺便说一句,使用名称作为foo和goo并不是一个好主意。我想我仍然不理解您的程序,您也是如此。

我宁愿先坚持使用较小的程序。还可以考虑使用代替通过(is)/2进行的模运算。 Here就是这样的建议改进,大概是针对您的同事的问题。

并且:系统收到有关单例变量的警告,无论如何都需要解决。那就是s/Foo_List/Foo_list/