我是 Prolog 的新手,我需要从列表中删除重复项,如下例所示。
?- remove([a,a,b,c,a,a,b,c,b,a,a],X).
X = [a,b,c,a,b,c,b,a]
我是 Prolog 的新手,我需要从列表中删除重复项,如下例所示。
?- remove([a,a,b,c,a,a,b,c,b,a,a],X).
X = [a,b,c,a,b,c,b,a]
如果我理解正确,您需要删除相邻的重复项。只需复制跳过第一个相邻元素的元素。我会让你完成代码...
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 !!
编辑错误指出,这种天真的 remove/2 是错误的。我已经更正了添加 remove/3 谓词,该谓词对见证进行了复制,即元素前瞻。
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 !!