Search code examples
prologreturn-value

Prolog predicate - returns list with duplicates removed from specific predicate


I'm a complete noob trying to write predicates and I've come a bit stuck. Earlier, I made a predicate called remDuplicates/2 which would state true, if the 2nd list of the predicate, was the 1st list with any duplicates removed. Please see the code below for the predicate I'm using.

   remDuplicates([], []).
   remDuplicates([H|T], [H|T1]) :- subtract(T,[H],T2), remDuplicates(T2, T1).

However, now I'm trying to create a new predicate, that uses remDuplicates to remove duplication from a single list, called remT/1. remT/1 that takes a single parameter, should use the remDuplicates predicate to remove any duplication, and then return the new list (without any duplication).

I've made an attempt as to how it should start but really, I have no idea where to go with it. Please see the start of my attempt below;

  remT([]).
  remT([H|T]) :- remDuplicates([H|T],[H|T]).

Would really appreciate help on this. Thanks.


Solution

  • As Boris told you, in Prolog there is no such thing as "returning", however, you can call your remDuplicates/2 like this:

    remDuplicates([1,2,2,3,4,5,7,5], T).
    

    This way, T will be the final list with no duplicates. You can then use it inside a bigger predicate or just run it on the terminal, since it will print on the screen something like T = [1,2,3,4,5,7].

    You can also check out the sort/2 predicate, which has a similar result as yours, already built in to SWI-Prolog.

    Hope it helped,
    André Pinto