开发者

How can I delete specific appearances of elements from an array in Prolog?

I want to delete only second appearance of each element in given array and return the result in a new array. The given array can have have atomic elements but also can have list like element within it.

the predicate should be called like this: delete_second(L1,L2).

L1=[1,2,4,1,[1,2,3,[4]],开发者_如何学运维2,1]

L2=[1,2,4,[1,3,[]],2,1].


You might use two accumulator lists. In one accumulator you would have the items that appeared just once, and on the other accumulator you would have the items that appeared more than once. So you would have to go through all the items of the input list updating those accumulators and selecting and discarding the item from the output list if required.

Something like:

delete_second(In, Out):-
delete_second(In, [], [], _, _, Out).

delete_second([], Once, Twice, Once, Twice, []):- !.
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [Y|Out]):-
  delete_second(X, Once, Twice, MOnce, MTwice, Y),
  !,
  delete_second(Tail, MOnce, MTwice, NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [X|Out]):-
  member(X, Twice),
  !,
  delete_second(Tail, Once, Twice, NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, Out):-
  append(OnceP, [X|OnceT], Once),
  append(OnceP, OnceT, MOnce),
  !,
  delete_second(Tail, MOnce, [X|Twice], NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [X|Out]):-
  !,
  delete_second(Tail, [X|Once], Twice, NOnce, NTwice, Out).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜