我需要编写一个程序来查找两个列表的交集。我不能使用 cut 并且结果列表中不应该有任何重复的元素。
这是我的代码:
intersection([],_,[]).
intersection([X|Xs],Y,[X|Zs]) :-
member(X,Y),
intersection(Xs,Y,Zs).
intersection([_|Xs],Y,Zs) :-
intersection(Xs,Y,Zs).
当我运行以下查询时,我得到以下答案:
?- intersection([a,b,c,a],[a,v,c],L).
L = [a, c, a] ;
L = [a, c] ; % <---------- this is only answer I want to get
L = [a, a] ;
L = [a] ;
L = [c, a] ;
L = [c] ;
L = [a] ;
L = [].
我能做什么?我要获取
L = [a,c]
没有别的……你能帮忙吗?
最佳答案
在 my answer对于相关问题“Intersection and union of 2 lists”,我提出了逻辑纯谓词list_list_intersectionSet/3
.它应该符合您对 T 的要求!
这是 list_list_intersectionSet/3
的刷版,这是基于:
if_/3
, tfilter/3
, dif/3
和 memberd_t/3
. 开始了:
list_list_intersectionSet([] ,_ ,[]).
list_list_intersectionSet([A|As0],Bs,Cs0) :-
if_(memberd_t(A,Bs), Cs0 = [A|Cs], Cs0 = Cs),
tfilter(dif(A),As0,As),
list_list_intersectionSet(As,Bs,Cs).
让我们看看它在行动!
?- list_list_intersectionSet([a,b,c,a],[a,v,c],L).
L = [a,c].
关于list - Prolog中没有重复元素的两个列表的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31635851/