Search code examples
listprologprolog-dif

Remove both the value and all duplicates of that value in a list in prolog


I'm having some trouble removing values from a list in prolog. I have a list of colors and I want to add a list of colors to it and keep all the values that have no duplicate and remove the rest.

[green, red, blue, purple, yellow, brown, orange, black, purple]

so purple appears twice in this list and I want to remove both of them. This is the list I want to be returned.

[green, red, blue, yellow, brown, orange, black]

I currently have this to remove all the duplicates but I can't get both purples out.

mymember(X,[H|_]) :- X==H,!.
mymember(X,[_|T]) :- mymember(X,T).

not(A) :- \+ call(A).

set([],[]).
set([Head|Tail],[Head|Out]) :-
    not(mymember(Head,Tail)),
    set(Tail, Out).
set([Head|Tail],Out) :-
    mymember(Head,Tail),
    set(Tail, Out).

this is the result I get now:

[green, red, blue, yellow, brown, orange, black, purple]

Solution

  • The simple way...a one-liner:

    singletons(Xs,Zs) :-
      findall( X , ( append(P,[X|S],Xs), \+member(X,P), \+member(X,S) ) , Zs )
      .