Re: Count lists elements




Hi all,
I have a problem, I need to write a program, which finds the element in
a list which repeats most often time. Lets say, I have such query:
?- most_often([a,b,c,a,v,s,a,b,t,a], K).
K = a.

I tried several ways, but no luck... Can anybody help me?

It would be more convincing if you showed some of the work.

--- Jan

This problem I find is easily solved in CHR (untested code):


:- chr_constraint solve/3, max/2, elements/1, get/2, count/2.

solve(Elements, MaxElem, MaxNum)
<=> max(-1, _), elements(Elements), get(MaxElem, MaxNum).

elements([E|Es]) <=> elem(E), elements(Es).
elements([]) <=> true.

elem(E), count(E, C) <=> C1 is C+1, count(E, C1).
elem(E) <=> count(E, 1).

count(E, C) \ max(M, _) <=> C > M | max(C, E).

get(R1, R2), max(M, E) <=> R1 = M, R2 = E.
.