Question

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).
Was it helpful?

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).

OTHER TIPS

Or using only built-ins. if you wanted to just get the job done:

notcommon(L1, L2, Result) :-

    intersection(L1, L2, Intersec),
    append(L1, L2, AllItems),
    subtract(AllItems, Intersec, Result).

    ?- notcommon([a,b,c,d], [a,b,e,f], X).
    X = [c, d, e, f].

Deliberately avoiding the built ins for this that @chac mentions, this is an inelegant way that does the job.

notcommon([], _, []).

notcommon([H1|T1], L2, [H1|Diffs]) :-
    not(member(H1, L2)),
    notcommon(T1, L2, Diffs).

notcommon([_|T1], L2, Diffs) :-
    notcommon(T1, L2, Diffs).

alldiffs(L1, L2, AllDiffs) :-
    notcommon(L1, L2, SetOne),
    notcommon(L2, L1, SetTwo),
    append(SetOne, SetTwo, AllDiffs).


    ? alldiffs([a,b,c,d], [a,b,e,f], X).
    X = [c, d, e, f] .
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top