prolog - Remove duplicate from list -


i trying remove duplicate list false, 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). 

frankly, implementation of predicates remov/2 , member/2 leaves a lot desired.

why? 5 of 6 clauses "use" meta-logical constructs (!)/0 , not/1. ruins declarative aspects, forces you&me focus on vast number of painstaking details regarding procedural execution aspects. details, see , .

as alternative, suggest following implementation of remov/2:

remov(xs,ys) :-     ( ground(xs) -> sort(xs,ys)    ; throw(error(instantiation_error,remov/2))    ). 

let's take code apart! trick use builtin predicate sort/2:

  • the builtin predicate sort/2 sorts lists of prolog terms according standard order.

  • sort/2 eliminates duplicate items.

  • depending on concrete instantiation, sort/2 may not preserve .

  • sort/2 logically sound (the term order safe) if use ground data.

sample queries:

?- remov([1,2,3,1,2],xs). xs = [1, 2, 3].  ?- remov(xs,ys). error: arguments not sufficiently instantiated 

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -