Here's how you could do it using if_/3
and (=)/3
:
count([], 0, _, []).
count([E|Es], N, E, L) :-
skip_(Es, 1,N, E, L).
skip_([], N,N, _, []).
skip_([E|Es], N0,N, X, Xs) :-
if_(E = X,
( N1 is N0+1, skip_(Es,N1,N,X,Xs) ),
( N0 = N, Xs = [E|Es] )).
Sample queries:
?- count([1,1,1,2], N, X, L).
N = 3, X = 1, L = [2].
?- count([1,1,1,2,2,1], N, X, L).
N = 3, X = 1, L = [2,2,1].
?- count([1], N, X, L).
N = X, X = 1, L = [].
?- J = [_,_,_], count(J, N, X, L).
J = [X, X, X], N = 3, L = []
; J = [X, X,_A], N = 2, L = [_A] , dif(_A,X)
; J = [X,_A,_B], N = 1, L = [_A,_B], dif(_A,X).
Note that count/4
can handle lists containing non-integers just as well:
?- count([a,a,a,b,b,c], N, X, L).
N = 3, X = a, L = [b,b,c].
count([1,1,1,2], N, X, L)
? I don't understand why in your exampleL
is not[1,2,2]
. – falsecount([1,2], N, X, L)
? ReallyL = [2]
? – falseselect(X,[X|T],K )
is rather strange: select/3 is usually called with select(X, Domain, Without_X), that is, X position unknown in Domain list. In the end, it reduces L to T. Nothing other ! – CapelliC