Delete both the value and all duplicates of this value in the list in the prolog

I'm having trouble deleting values ​​from a list in the prolog. I have a list of colors, and I want to add a list of colors to it and save all the values ​​that do not have duplicates, and delete the rest.

[green, red, blue, purple, yellow, brown, orange, black, purple]

therefore magenta appears twice in this list, and I want to remove both of them. This is the list I want to return.

[green, red, blue, yellow, brown, orange, black]

I currently have this to remove all duplicates, but I cannot get both magenta.

mymember(X,[H|_]) :- X==H,!.
mymember(X,[_|T]) :- mymember(X,T).

not(A) :- \+ call(A).

set([],[]).
set([Head|Tail],[Head|Out]) :-
    not(mymember(Head,Tail)),
    set(Tail, Out).
set([Head|Tail],Out) :-
    mymember(Head,Tail),
    set(Tail, Out).

this is the result i am getting now:

[green, red, blue, yellow, brown, orange, black, purple]
+4
source share
5 answers

Easy way ... single line:

singletons(Xs,Zs) :-
  findall( X , ( append(P,[X|S],Xs), \+member(X,P), \+member(X,S) ) , Zs )
  .
+3
source

, tfilter/3 list_uniqmember_t/3!

list_uniqs(Es, Us) :-
   tfilter(list_uniqmember_t(Es), Es, Us).

, OP, :

?- list_uniqs([green,red,blue,purple,yellow,brown,orange,black,purple], Xs).
Xs = [green,red,blue,yellow,brown,orange,black]. % succeeds deterministically

?

?- list_uniqs([A,B,A], []).
   A=B
;  false.

?- list_uniqs([A,B,A], [_]).
dif(A,B).

?- list_uniqs([A,B,A], [_,_]).
false.

?- list_uniqs([A,B,A], Xs).
   Xs = [] ,     A=B
;  Xs = [B], dif(A,B).

! - ?

?- list_uniqs([A,B,C],Xs).
   Xs = []     ,     A=B           ,     B=C
;  Xs = [C]    ,     A=B           , dif(B,C)
;  Xs = [B]    ,               A=C , dif(B,C)
;  Xs = [A]    ,           dif(A,C),     B=C 
;  Xs = [A,B,C], dif(A,B), dif(A,C), dif(B,C).

!

+3

, . → ; delete/3, :

remdup([], _, []).
remdup([H|T], X, R) :-
    (   H == X
    ->  (   member(X, T)
        ->  delete(T, X, R)     % only delete if it in the list more than once
        ;   R = [H|R1],
            remdup(T, X, R1)
        )
    ;   R = [H|R1],
        remdup(T, X, R1)
    ).

, select/3, delete/3:

remdup(L, X, R) :-
    (select(X, L, L1), select(X, L1, L2))
->  delete(L2, X, R)
;   L = R.

select/3 . , . , , .


, ( , ):
remdup([], []).
remdup([H|T], R) :-
    (   select(H, T, T1)
    ->  delete(T1, H, R1),
        remdup(R1, R)
    ;   R = [H|R1],
        remdup(T, R1)
    ).
+1

, :

my_delete(Res, [], Res).
my_delete(Colorslist, [Head|Tail], R) :-  
    my_delete_worker(Colorslist, Head, Result), 
    my_delete(Result, Tail, R).

my_delete_worker([], _, []).
my_delete_worker([X|T], X, R) :-
    my_delete_worker(T, X, R).
my_delete_worker([H|T], X, [H|R]) :-
    X \= H,
    my_delete_worker(T, X, R).

. , . lurker!

0

( : -)

singletons(Xs, Zs) :- findall(X, (select(X,Xs,Ys), \+memberchk(X,Ys)), Zs).
0

Source: https://habr.com/ru/post/1612588/


All Articles