cip
cip

Reputation: 79

Remove duplicate from list

I am trying to remove duplicate from list but I get false, this is my code :

remov([],[]):-!.
remov([T|Q],[T|R]):-not(member(T,R)),remov(Q,[T|R]).
remov([T|Q],R):-member(T,R),!,remov(Q,R).

member(E,[]):-!,fail.
member(T,[T|Q]):-!.
member(E,[T|Q]):-member(E,Q).

Upvotes: 0

Views: 487

Answers (1)

repeat
repeat

Reputation: 18726

The above implementation of predicates remov/2 and member/2 excessively "use" the meta-logical constructs (!)/0 and not/1, which ruins almost all declarative aspects—forcing us to focus on a vast number of painstaking details. For details, see and .

Let's re-implement remov/2 based on iwhen/2 and sort/2, like so:

remov(Xs,Ys) :- 
   iwhen(ground(Xs), sort(Xs,Ys)).

How does this work?

  • The builtin predicate sort/2 sorts lists of Prolog terms according to the standard order, eliminating duplicate items in the process. Note that sort/2 may not preserve if the input list contains variables.

  • iwhen/2 ensures sufficient instantiation when using sort/2.

Sample queries:

?- remov([1,2,3,1,2],Xs).
Xs = [1,2,3].

?- remov(Xs,Ys).
ERROR: Arguments are not sufficiently instantiated

Upvotes: 1

Related Questions