user1704850
user1704850

Reputation: 201

Remove adjacent duplicates from a list prolog

I'm new to Prolog and I need to remove duplicates from a list like shown in the example below.

?- remove([a,a,b,c,a,a,b,c,b,a,a],X).
X = [a,b,c,a,b,c,b,a]

Upvotes: 1

Views: 1833

Answers (1)

CapelliC
CapelliC

Reputation: 60034

If I understand correctly, you need to remove adjacents duplicates. Just copy the elements skipping the first of adjacents. I'll let you to complete the code...

remove([X,X|Rest], [X|Rest1]) :-
   !,   % this commit avoid the logical alternative you'll code below
   .... % recurse to get Rest1 from Rest
remove([X|Rest], [X|Rest1]) :-
   % recurse to get Rest1 from Rest
% remember the base case !!

edit as false pointed out, such naive remove/2 is buggy. I've corrected adding a remove/3 predicate, that does the copy accounting for a witness, i.e. with an element lookahead.

remove([X|Xs], [X|Ys]) :-
  remove(X, Xs, Ys).
remove(X, [X|Xs], Ys) :-
  !,  % discard the duplicate
  ... % recurse to get Ys from Xs, with same witness
remove(_, [X|Xs], [X|Ys]) :-
  ... % the cut above ensure that here we must change witness when recursing
% as always, remember the base case !!

Upvotes: 1

Related Questions