Search code examples
prologswi-prolog-for-sharing

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


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


Solution

  • 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