listprologsymmetric-difference

Prolog lists difference


I'm trying to make program in prolog that will do something like this:

diffSet([a,b,c,d], [a,b,e,f], X).
X = [c,d,e,f]

I wrote this:

diffSet([], _, []).
diffSet([H|T1],Set,Z):- member(Set, H), !, diffSet(T1,Set,Z).
diffSet([H|T], Set, [H|Set2]):- diffSet(T,Set,Set2).

But in that way I can only get elements from the first list. How can I extract the elements from the second one?

@edit: member is checking if H is in Set

member([H|_], H).
member([_|T], H):- member(T, H).

Solution

  • There is a builtin that remove elements from the list:

    diffSet([], X, X).
    
    diffSet([H|T1],Set,Z):-
     member(H, Set),       % NOTE: arguments swapped!
     !, delete(T1, H, T2), % avoid duplicates in first list
     delete(Set, H, Set2), % remove duplicates in second list
     diffSet(T2, Set2, Z).
    
    diffSet([H|T], Set, [H|Set2]) :-
     diffSet(T,Set,Set2).