You could write a predicate occurrences/5 that is true if the second and third arguments occur equally often in the list that is the first argument. The 4th and 5th arguments are the corresponding counters. Then the predicate occurrences/1 is the calling predicate:
occurrences(List) :-
occurrences(List,a,b,0,0).
occurrences([],_A,_B,N,N).
occurrences([A|Xs],A,B,N0,M) :-
N1 is N0+1,
occurrences(Xs,A,B,N1,M).
occurrences([B|Xs],A,B,N,M0) :-
M1 is M0+1,
occurrences(Xs,A,B,N,M1).
occurrences([X|Xs],A,B,N,M) :-
dif(A,X),
dif(B,X),
occurrences(Xs,A,B,N,M).
You start with the counters at 0 and depending on the head of the list being equal to A
or B
the corresponding counter is incremented or no counter is incremented if the head differs from both. Now let's see the results for your given examples:
?- occurrences([a,a,b,b]).
true ;
false.
?- occurrences([a,a,a,b,b]).
false.
However, I think a predicate occurrences/3 that lets you specify the two elements would be more useful:
occurrences(List,A,B) :-
dif(A,B),
occurrences(List,A,B,0,0).
Then your example queries would look like this:
?- occurrences([a,a,b,b],a,b).
true ;
false.
?- occurrences([a,a,a,b,b],a,b).
false.
You could also ask which elements occur equally often:
?- occurrences([a,a,b,b,c,c,d],X,Y).
X = a,
Y = b ;
X = a,
Y = c ;
X = b,
Y = a ;
X = c,
Y = a ;
X = b,
Y = c ;
X = c,
Y = b ;
dif(X, d),
dif(X, c),
dif(X, c),
dif(X, b),
dif(X, b),
dif(X, a),
dif(X, a),
dif(X, Y),
dif(Y, d),
dif(Y, c),
dif(Y, c),
dif(Y, b),
dif(Y, b),
dif(Y, a),
dif(Y, a).
The last solution corresponds to two elements that do not appear in the list at all, since they both appear equally often, namely 0 times. If you want to use the predicate in the other direction, that is, to ask which lists there are such that two given elements appear equally often, you have to prefix a goal that is limiting the length of the list at the time of the predicate call, e.g.:
?- length(L,_),occurrences(L,a,b).
L = [] ;
L = [_G150],
dif(_G150, b),
dif(_G150, a) ;
L = [a, b] ;
L = [b, a] ;
L = [_G116, _G119],
dif(_G116, b),
dif(_G116, a),
dif(_G119, b),
dif(_G119, a) ;
L = [a, b, _G162],
dif(_G162, b),
dif(_G162, a) ;
L = [a, _G159, b],
dif(_G159, b),
dif(_G159, a) ;
L = [b, a, _G162],
dif(_G162, b),
dif(_G162, a) ;
.
.
.