排除列表中所有出现的最小数量

编程入门 行业动态 更新时间:2024-10-17 07:33:44
本文介绍了排除列表中所有出现的最小数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

作为Prolog新手,我尝试定义一个谓词filter_min/2,该谓词使用两个列表来确定第二个列表是否与第一个列表相同,但是所有出现的最小数量都被删除.

As a Prolog newbie, I try to define a predicate filter_min/2 which takes two lists to determine if the second list is the same as the first, but with all occurrences of the minimum number removed.

对具有预期结果的查询进行采样:

Sample queries with expected results:

?- filter_min([3,2,7,8], N). N = [3,7,8]. ?- filter_min([3,2,7,8], [3,7,8]). true.

我尝试过,但总是得到相同的结果:false.我不知道问题是什么.我需要帮助!

I tried but I always get the same result: false. I don't know what the problem is. I need help!

这是我的代码:

filter_min(X,Y) :- X == [], write("ERROR: List parameter is empty!"), !; min_list(X,Z), filter(X,Y,Z). filter([],[],0). filter([H1|T1],[H2|T2],Z) :- \+ number(H1), write("ERROR: List parameter contains a non-number element"), !; H1 \= Z -> H2 is H1, filter(T1,T2,Z); filter(T1,T2,Z).

推荐答案

您的代码有两个问题:

  • filter([],[],0).在处理任何最小值不为0的列表时将无法统一,这不是您想要的.您希望它统一起来,而不考虑结束递归的最小值.
  • 您编写filter([H1|T1],[H2|T2],Z)的方式及其主体将使这两个列表始终具有相同数量的元素,而实际上第二个列表应至少少一个.
  • filter([],[],0). will not unify when working with any list that does not have 0 as its minimum value, which is not what you want. You want it to unify regardless of the minimum value to end your recursion.
  • The way you wrote filter([H1|T1],[H2|T2],Z) and its body will make it so that the two lists always have the same number of elements, when in fact the second one should have at least one less.

filter/3的正确实现如下:

filter([],[],_). filter([H1|T1],L2,Z):- \+ number(H1), write("ERROR: List parameter contains a non-number element"), !; H1 \= Z -> filter(T1,T2,Z), L2 = [H1|T2]; filter(T1,L2,Z).

更多推荐

排除列表中所有出现的最小数量

本文发布于:2023-11-30 07:18:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649142.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最小   数量   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!