Reputation: 679
I am trying to understand the unique predicate:
for example:
unique([H|T],[H|TU]) :- delete(T,E,TN), unique(TN,TU).
delete(T,E,TN) is true if a list TN is identical to a list T
after removing all occurrences of an element E.
delete([H|T],H,TN) :- delete(T,H,TN).
delete([H|T],E,[H|TN]) :- \+ H=E, delete(T,E,TN).
delete([],_,[]).
unique(['a','b','a','c'],X).
X = [a, b, c] <- Enter was pressed
Yes
So it comparing two lists T = ['a', 'b', 'd', 'f', 't'] TN =['a', 'b', 'd']
removes the occurrences of common elements
This is the entire code:
% delete(L,E,LN) is true if a list LN is identical to a list L
% after removing all occurences of an element E.
delete([H|T],H,TN) :- delete(T,H,TN).
delete([H|T],E,[H|TN]) :- \+ H=E, delete(T,E,TN).
delete([],_,[]).
% unique(L,LN) is true if a list LN is identical to a list L
% without all repeated elements.
unique([H|T],[H|TU]) :- delete(T,E,TN), unique(TN,TU).
unique([],[]).
please guide here thanks a lot
Upvotes: 1
Views: 1575
Reputation: 12972
First of all you need to change
unique([H|T],[H|TU]) :- delete(T,E,TN), unique(TN,TU).
to:
unique([H|T],[H|TU]) :- delete(T,H,TN), unique(TN,TU).
What unique predicate does is to delete element duplicates in the list and keep only the first occurrence. But your predicate fails because you don't handle the case of empty list so if you add the clause:
unique([],[]).
It works fine:
?- unique([a,b,a,c],X).
X = [a, b, c].
In this example it calls unique([a,b,a,c],X)
. which calls delete([b,a,c],a,TN)
and TN becomes [b,c]
, calls unique([b,c],TU)
and finally returns [a|TU]
.
TU is found recursively with the same way by calling:unique([b,c],TU)
which returns TU=[b|TU2]
where TU2 given recursively by calling: unique([c],TU2)
which returns [c]
.
Upvotes: 2