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,3,1,1],0,X)
the result would be X=[ [1,3],[2,3],[3,1][1,2] ]
aka each sublist is [element,occurrences]
In my case i believe there is something wrong with the base case but I cannot solve it. Can you help me?
%append an element to a list
append([ ],Y,Y).
append([X|Xs],Ys,[X|Zs]):-append(Xs,Ys,Zs).
%c is the counter beginning with 0
count(_,[],_,[]).
count(X,[X],C,[L]):-count(X,[],C,[L|[X,C]]).
%increase counter
count(X,[X|Tail],C,L):-Z is C+1,count(X,Tail,Z,L).
count(X,[Head|Tail],C,[L]):-append(L,[X,C],NL),count(Head,Tail,1,NL).
Here's another try of doing run-length encoding, based on clpfd!
Based on
if_/3and(=)/3, we definelist_rle/2:list_rle([],[]). list_rle([X|Xs],[N*X|Ps]) :- list_count_prev_runs(Xs,N,X,Ps). list_count_prev_runs(Es,N,X,Ps) :- N #> 0, N #= N0+1, list_count_prev_runs_(Es,N0,X,Ps). list_count_prev_runs_([],0,_,[]). list_count_prev_runs_([E|Es],N,X,Ps0) :- if_(X=E, list_count_prev_runs(Es,N,X,Ps0), (N = 0, Ps0 = [M*E|Ps], list_count_prev_runs(Es,M,E,Ps))).Sample queries:
encode/decode #1
encode/decode #2
How about something a little more general?