How to remove the repeated members in a simple list [ prolog ]

梦想的初衷 提交于 2020-01-05 08:27:44

问题


EDIT : How can I remove the repeated members in a simple list

for example :

[a,b,b,b,c,c,e] in this list the are 2 c and 3 b and I want to remove all members that's repeated the result should be like this [a,e]

keep in mind I'm just learning the basic just for an assignment and I'm using the swish online compiler


回答1:


I have edited my previous code. My previous code gives the output in reverse order.

I used cut here so that it wouldn't backtrack all the possibilities of takeout function. Hope this helps you.

I think this is the solution you were looking for.

takeout(X,[X|R],R).
takeout(X,[F|Fs],[F|S]):- takeout(X,Fs,S).
/* takeout function is used to delete
given element from the list.*/

ap([],L,L).
ap(L,[],L).
ap([H|T],L,[H|Z]):- ap(T,L,Z).
/* ap function is used to append
elements to a list. */


unique([X],_,[X]).
unique([H|T],X,Z):-  ( member(H,T) ; member(H,X) ) , ap([H],X,Xs) , takeout(H,[H|T],B) ,!, unique(B,Xs,Z).
unique([H|T],X,[H|Z]):- \+member(H,T) , \+member(H,X) , takeout(H,[H|T],Ts) ,!, unique(Ts,X,Z).

output

?- unique([1,2,2,3,3,4],[],M).

M= [1,4]
false

For adding the elements of the list

sum([H,H1|T],Z):- Z1 is H+H1 , sum([Z1|T],Z).
sum([X],X).

?- sum([1,2,3],Z).
   Z=6
   false

But this method is in-place. The list gets modified.




回答2:


Even I started learning prolog recently. so I implemented the above problem using basic functions. Coming to the logic I used.

Suppose if the list is [1,2,2,3,3,4], create List named Duplicate(initially empty).

1. we will check if the Head element is present in the tail of the list or Duplicate List.

2. If present in either of Lists then add the Head element to List Duplicate, now takeout the Head element.

3. Else if not present in tail and Duplicate, takeout the Head element and add it to List Answer.

4. Repeat the above steps until the original list becomes empty.

takeout(X,[X|R],R).
takeout(X,[F|Fs],[F|S]):- takeout(X,Fs,S).
/* takeout function is used to delete
given element from the list.*/

ap([],L,L).
ap(L,[],L).
ap([H|T],L,[H|Z]):- ap(T,L,Z).
/* ap function is used to append
elements to a list. */


unique([],_,Z):- write(Z),!.
unique([H|T],X,Z):-  ( member(H,T) ; member(H,X) ) , ap([H],X,Xs) , takeout(H,[H|T],B) , unique(B,Xs,Z).
unique([H|T],X,Z):- \+member(H,T) , \+member(H,X) , ap([H],Z,Zs) , takeout(H,[H|T],Ts) , unique(Ts,X,Zs).

OUTPUT



来源:https://stackoverflow.com/questions/59084998/how-to-remove-the-repeated-members-in-a-simple-list-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!