In addition to what others wrote, consider using the dif/2 constraint:
occurrences(_, [], []).
occurrences(X, [X|Ls], [X|Rest]) :-
occurrences(X, Ls, Rest).
occurrences(X, [L|Ls], Rest) :-
dif(X, L),
occurrences(X, Ls, Rest).
You can now use the predicate in all directions, for example:
?- occurrences(X, [a,a,b], Os).
X = a,
Os = [a, a] ;
X = b,
Os = [b] ;
Os = [],
dif(X, b),
dif(X, a),
dif(X, a) ;
false.
The last solution means that the list of occurrences is empty if X is different from both a
and b
.