I tried to implement a predicate count/5 that given a List, an element E and an initial count of 0 it is supposed to return the total number of time E shows up consecutively and the remaining list.
So by count([1,1,1,2,3,4,1],1,0,COUNT,REMAINING_LIST) the following result is expected :
COUNT = 3 , REMAINING_LIST = [2,3,4,1]
I implemented the following 2 versions of it :
count1([],_,C,C,[]).
count1([E|T],E,C,EC,L) :-
!,
C1 is C + 1,
count1(T,E,C1,EC,L).
count1([H|T],E,C,C,[H|T]) :- H \== E.
count2([],_,C,C,[]).
count2([H|T],E,C,EC,L) :-
H == E,
!,
C1 is C + 1,
count2(T,E,C1,EC,L).
count2([H|T],E,C,C,[H|T]) :- H \== E.
Both seem to work just fine for regular lists - I am aware that some edge cases are not taken into account - but when I decided to run the following query out of curiosity I got 2 completely different results :
count1([1,1,X,X,2],1,0,S,Z).
S = 4,
X = 1,
Z = [2]
count2([1,1,X,X,2],1,0,S,Z).
S = 2,
Z = [X, X, 2]
Any explanation on why these 2 queries differ when it comes to their result would be appreciated.
Edit :
One thing I thought of is that probably in the following call of count1 :
count1([X|T],1,2,EC,L)
X turns out to be 1 so that the call complies with the defined rule that the head element of the list should be equal to the element we are looking for / that is being counted.