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 prolog-cut , logical-purity.
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/2sorts lists of prolog terms according standard order.sort/2eliminates duplicate items.depending on concrete instantiation,
sort/2may not preserve logical-purity.sort/2logically 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
Post a Comment