Hello I am trying to make a program in Prolog that given a list it counts the occurrences of each successive element in the list as follows:
count(1,[1,1,1,2,2,2
Another solution (tail recursive) is this:
run_length_encode( Xs , Ys ) :- % to find the run length encoding of a list ,
rle( Xs , 1 , Ys ) . % - just invoke the helper
rle( [] , _ , [] ) . % the run length encoding of the empty list is the empty list
rle( [A] , N , [X:N] ) . % A list of length 1 terminates the run: move the run length to the result
rle( [A,A|Xs] , N , Ys ) :- % otherwise, if the run is still going
N1 is N+1 , % - increment the count,
rle( [A|Xs] , N1 , Ys ) % - and recurse down
. %
rle( [A,B|Xs] , N , [A:N|Ys] ) :- % otherwise, if the run has ended
A \= B , % - we have a break
rle( [B|Xs] , 1 , Ys ) % - add the completed run length to the result and recurse down
. %