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_/3
and(=)/3
, we definelist_rle/2
:Sample queries:
encode/decode #1
encode/decode #2
How about something a little more general?