list - Prolog中没有重复元素的两个列表的交集

标签 list prolog duplicates

我需要编写一个程序来查找两个列表的交集。我不能使用 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/

    相关文章:

    c++ - std::find 在 glm::vec3 的 vector 中不起作用(OpenGLTriangle 法线具有折角)

    php - 连接唯一或删除重复字符串 php/mysql

    python - 如何对PIL图像的所有像素求和?

    html - 在@media CSS 查询上设置透明悬停的问题

    prolog - 用于从 Prolog 中的复合术语中删除某些术语的谓词

    list - Prolog:元素不存在于列表中

    python - 一旦搜索到列表中的字符串,有什么方法可以获取列表的名称吗?

    Python - 实例变量列表的最小值

    prolog - 检查列表是否仅包含零

    php - 根据子数组重复值删除数组项,然后按自定义顺序排序