prolog - 给出结果后Prolog卡住了
问题描述
所以我有这个知识库,我正在努力实现以注释形式给出的代码中的目标。
%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.
解决方案
是什么原因造成的?
假设您的意思是循环goo_sum(X, 20)
:
对于查询,我得到了很多答案。其实,对我来说太多了。所以我会考虑
?- goo_sum(X, 20), false.
哪个循环。A 原因是以下非常紧凑的故障片
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 是 NUMH + PREV_RESULT。
您需要以某种方式修复剩余部分,否则循环将保留。
顺便说一句,使用名称作为 foo 和 goo 不是一个好主意。我还是不明白你的程序,我想你也是。
我宁愿先坚持较小的程序。还可以考虑使用clpfd代替调制算法 via (is)/2
。这是一个这样的改进建议——大概是针对你同事的一个问题。
并且:您收到了一些关于单例变量的系统警告,无论如何您都需要修复它。那是s/Foo_List/Foo_list/
推荐阅读
- javascript - 基于评级的搜索过滤器
- c++ - 使用什么数据结构来创建甘特图的表示?
- asp.net-mvc - 在不安装实体框架 nuget 的情况下使用 DbFunctions 方法
- azure - 有什么方法可以确保任何 azure 服务计划在一个 azure 订阅中具有唯一的静态出站 IP 地址?
- sql-server - EF Core 在大循环中存在 ABP 性能问题
- intellij-idea - Intellij IDEA 中的新 HTTP 客户端如何自动解析响应
- java - 如何从 Java 中的文本文件中读取格式化数据
- c++ - 计算出有多少客户端可以连接到我正在使用的一些 tcp 服务器代码
- mysql - 加入价值 MySQL
- python - 可以或如何在 Google Cloud Functions 上使用 Python asyncio?