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

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

问题描述

作为 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天全站免登陆