2个列表的交集和并集 [英] Intersection and union of 2 lists

查看:144
本文介绍了2个列表的交集和并集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开始学习序言(我使用SWI-prolog),我做了一个简单的练习,其中有2个列表,我想计算它们的交集和并集. 这是我的代码,效果很好,但是我问自己是否有更好的方法,因为我不喜欢使用

i'm starting up learning prolog (i use SWI-prolog) and i did a simple exercise in which i have 2 lists and i want to calculate their intersection and union. Here is my code that works pretty well but i was asking myself if there is a better way to do it as i don't like to use the CUT operator.

intersectionTR(_, [], []).
intersectionTR([], _, []).
intersectionTR([H1|T1], L2, [H1|L]):-
    member(H1, L2),
    intersectionTR(T1, L2, L), !.
intersectionTR([_|T1], L2, L):-
    intersectionTR(T1, L2, L).

intersection(L1, L2):-
    intersectionTR(L1, L2, L),
    write(L).


unionTR([], [], []).
unionTR([], [H2|T2], [H2|L]):-
    intersectionTR(T2, L, Res),
    Res = [],
    unionTR([], T2, L),
    !.
unionTR([], [_|T2], L):-
    unionTR([], T2, L),
    !.

unionTR([H1|T1], L2, L):-
    intersectionTR([H1], L, Res),
    Res \= [],
    unionTR(T1, L2, L).
unionTR([H1|T1], L2, [H1|L]):-
    unionTR(T1, L2, L).

union(L1, L2):-
    unionTR(L1, L2, L),
    write(L).

请记住,我只希望有1个结果,而不是多个结果(即使正确),因此请使用以下代码运行代码:

Keep in mind that i want to have just 1 result, not multiple results (even if correct) so running the code with this:

?- intersect([1,3,5,2,4] ,[6,1,2]).

应退出:

[1,2]
true.

而不是

[1,2]
true ;
[1,2]
true ;
etc...

对于联合谓词也必须相同.
正如我所说的,我的代码效果很好,但是请提出更好的方法.
谢谢

The same must be valid for union predicate.
As i said my code works pretty well but please suggest better ways to do it.
Thanks

推荐答案

此外,不确定删除的原因,只要删除它们不会改变代码的声明性含义(按您的链接).例如:

Also, not sure why you're dead against cuts, so long as their removal would not change the declaritive meaning of the code, as per your link. For example:

inter([], _, []).

inter([H1|T1], L2, [H1|Res]) :-
    member(H1, L2),
    inter(T1, L2, Res).

inter([_|T1], L2, Res) :-
    inter(T1, L2, Res).

test(X):-
        inter([1,3,5,2,4], [6,1,2], X), !.

test(X).
X = [1, 2].

在我称为代码的测试位中,我只是说做交集,但我只对第一个答案感兴趣.谓词定义本身没有减少.

In the test bit where I call the code, I'm just saying do the intersection but I'm only interested in the first answer. There are no cuts in the predicate definitions themselves.

这篇关于2个列表的交集和并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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