I'm new to Prolog and I am trying to understand it.
I started with some simple program, this one should:
- check if an element is contained in the rest of the list
- if FALSE do nothing
- if TRUE add it to a second list. (only one occurrence of a char should be added to the second list).
Some examples with expected results:
?- occ([a,b,c,a,a,b,e,f,g], Y).
Y = [a,b].
?- occ([a,a,a,a,a], Y).
Y = [a].
?- occ([a,b,c,d,e,f,g], Y).
Y = [].
Here's the code I wrote, but I have some problems (it always returns true
).
occ([],[]).
occ([],_Y).
occ([X|Xs],[X|Y]) :-
occ(Xs,Y),
member(X,Xs),
not(member(X,Y)),
!.
occ([_X|_Xs],_Y).
I tried using the debugger and I found that the not(member(X,Y))
is always false
and in the binding section there is only X
and Xs
and never Y
. Any advice is much appreciated! Thank you.
UPDATE
I think I solved it, here's the code:
occ([],[]).
occ([X|Xs],[X|Y]) :-
occ(Xs,Y),
member(X,Xs),
not(member(X,Y)),
!.
occ([_X|_Xs],[]).
But I'm not really sure why it works now... in the 3-th occ
I changed the _Y
with []
..
But why does it change the results?