Intersection and union of 2 lists

后端 未结 7 1861
青春惊慌失措
青春惊慌失措 2020-11-27 07:41

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

7条回答
  •  不知归路
    2020-11-27 08:08

    I know this post is very old but I found a solution with minimum coding.

    % intersection
    intersection([],L1,L2,L3).
    intersection([H|T],L2,L3,[H|L4]):-member(H,L2),intersection(T,L3,L3,L4).
    % member
    member(H,[H|T]).
    member(X,[H|T]):-member(X,T).
    

    To test the above code you should not enter L3. Here is an examples.

    ?- intersection([w,4,g,0,v,45,6],[x,45,d,w,30,0],L).
    L = [w, 0, 45].
    

提交回复
热议问题