我是Prolog的新手,我需要从列表中删除重复项,如下例所示。
?- remove([a,a,b,c,a,a,b,c,b,a,a],X).
X = [a,b,c,a,b,c,b,a]
答案 0 :(得分:1)
如果我理解正确,您需要删除 adjacents 重复项。只需复制跳过第一个相邻元素的元素。我会让你完成代码......
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 !!
编辑,因为错误指出,这样的天真删除/ 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 !!