排除列表中所有出现的最小数量 [英] Excluding all occurrences of the minimum number in a list

查看:60
本文介绍了排除列表中所有出现的最小数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为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).

这篇关于排除列表中所有出现的最小数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆