Search code examples
prolog

How to remove duplicates from a list in SWI-Prolog?


I need to write a predicate remove_duplicates/2 that removes duplicate elements form a given list. For example:

?- remove_duplicates([a,a,b,c,c], List). List = [a,b,c] Yes

Please keep in mind I'm only learning SWI-Prolog for two days and only understand the basics of Prolog. This is what I have at the moment:

remove_duplicates([H | T], List) :- member(H, T), append(T, [], List1).

This works for the list [a,a,b,c] but not for lists where two elements in the tail are the same. I figured I somehow have to remove the Head to a temporary list, create a new Head and just repeat the predicate. I have no idea how to do that. Also, when the Head is not in the Tail, for example with lists like [a,b,b,c], the terminal just says False, because member(H, T) is not true.

Any ideas?


Solution

  • A simple and nice code to remove duplicates would be:

    remove_duplicates([], []).
    
    remove_duplicates([Head | Tail], Result) :-
        member(Head, Tail), !,
        remove_duplicates(Tail, Result).
    
    remove_duplicates([Head | Tail], [Head | Result]) :-
        remove_duplicates(Tail, Result).
    
    

    As described in Introduction to Prolog by Ulle Endriss