我是新來的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 !!
編輯虛假指出,這種天真的刪除/ 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 !!
'[a,a,a]'會發生什麼? –
'remove([X1,X2],[Y1,Y2])'應該是什麼答案? – false