Running a trace
in prolog can be very helpful in determining the answer to this sort of question. We'll do the trace manually here for illustration.
Let's look at your predicate:
once(X, [H | T]) :-
\+ X = H,
once(X, T).
once(X, [X | T]) :-
\+ member(X, T).
Let's consider now the query:
once(X, [b,a,a,c,b,a]).
First, Prolog attempts the first clause of your predicate. The head is once(X, [H|T])
and first expression is \+ X = H
, which will become:
once(X, [b|[a,a,c,b,a]]) :- % [H|T] instantiated with [b,a,a,c,b,a] here
% So, H is b, and T is [a,a,c,b,a]
\+ X = b,
...
X
is instantiated (be unified with) with the atom b
here, and the result of that unification succeeds. However, you have a negation in front of this, so the result of \+ X = b
, when X
is initially unbound, will be false since X = b
unifies X
with b
and is true.
The first clause thus fails. Prolog moves to the next clause. The clause head is once(X, [X|T])
and following is \+ member(X, T)
, which become:
once(b, [b|[a,a,c,b,a]]) :- % X was instantiated with 'b' here,
% and T instantiated with [a,a,c,b,a]
\+ member(b, [a,a,c,b,a]).
member(b, [a,a,c,b,a])
succeeds because b
is a member of [a,a,c,b,a]
. Therefore, \+ member(b, [a,a,c,b,a])
fails.
The second clause fails, too.
There are no more clauses for the predicate once(X, [b,a,a,c,b,a])
. All of them failed. So the query fails. The primary issue is that \+ X = H
(or even X \= H
, when X
is not instantiated, won't choose a value from the list that is not the same as the value instantiated in H
. Its behavior isn't logically what you want.
A more straight-on approach to the predicate would be:
once(X, L) :- % X occurs once in L if...
select(X, L, R), % I can remove X from L giving R, and
\+ member(X, R). % X is not a member of R
The select
will query as desired for uninstantiated X
, so this will yield:
?- once(c, [b,a,a,c,b,a]).
true ;
false.
?- once(b, [b,a,a,c,b,a]).
false.
?- once(X, [b,a,a,c,b,a]).
X = c ;
false.
As an aside, I'd avoid the predicate name once
since it is the name of a built-in predicate in Prolog. But it has no bearing on this particular problem.