Let's answer that with an example. Say we remove 2
, from [1,2,3]
. Then Prolog will evaluate it like this:
remove1(2,[1,2,3],R):
fail. % clause 1
fail. % clause 2
2 \= 1, remove1(2,[2,3],R'): % clause 3
fail. % clause 1
R = [1,3] % clause 2
2 \= 2... fail. % clause 3
\+member(2,[3]),R=[1,2,3] % clause 4
\+member(2,[2,3])... fail. % clause 4
(answers put in boldface)
So once Prolog has found the first answer, it backtracks, checks if 2
is a member of the tail T=[3]
(which it is not), and thus replies (based on the last clause) that [1,2,3]
is an answer as well.
It makes me wondering why you added the last clauses. If 2
cannot be found, Prolog would have answered the list anyway. So the program:
remove1(X,[],[]).
remove1(X,[X|T],T).
remove1(X,[H|T],[H|R]):-
X \= H,
remove1(X,T,R).
Would be sufficient.
If you however want the query to succeed only if it has deleted one occurrence, you should remove the first query as well. So:
remove1_force(X,[X|T],T).
remove1_force(X,[H|T],[H|R]):-
X \= H,
remove1(X,T,R).
Both predicates will only remove the first occurrence of X
in the list. So remove1_force(1,[1,2,3,1,2,3],R)
. Will only give one answer: R = [2,3,1,2,3]
.