【发布时间】:2019-10-05 03:41:42
【问题描述】:
所以我有这个知识库,我正在努力实现以 cmets 形式给出的代码中的目标。
%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]).
但是,goo 部分存在问题。当我只将 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.
【问题讨论】:
-
您可以
trace.您的程序查看它在哪些点上回溯并陷入无限递归。 -
我试过了,但是有很多检查正在进行,当我单独尝试助手时,他们返回一件事然后退出。 goo_sum(X,20) 例如。它只是给出 [i] 并停止。但是,当我完全运行 goo 时,我不明白。我得到了想要的结果,但它卡住了。
标签: prolog failure-slice