开发者

How do I count the number of elements in a list?

I need to write a small Prolog program to co开发者_运维百科unt the number of occurrence of each element in a list.

numberOfRepetition(input, result)

For example:

numberOfRepetition([a,b,a,d,c,a,b], X)

can be satisfied with X=[a/3,b/2,d/1,c/1] because a occurs three times, b occurs 2 times and c and d one time.


I don't want to give you the answer, so I gonna help you with it:

% Find the occurrences of given element in list
%
% occurrences([a,b,c,a],a,X).
% -> X = 2.

occurrences([],_,0).
occurrences([X|Y],X,N):- occurrences(Y,X,W),N is W + 1.
occurrences([X|Y],Z,N):- occurrences(Y,Z,N),X\=Z.

Depending on your effort and feedback, I can help you to get your answer.


Check out my answer to the related question "How to count number of element occurrences in a list in Prolog"! In that answer I present the predicate list_counts/2, which should fot your needs.

Sample use:

:- list_counts([a,b,a,d,c,a,b],Ys).
Ys = [a-3, b-2, d-1, c-1].

Note that that this predicate uses a slightly different representation for key-value pairs expressing multiplicity: principal functor (-)/2 instead of (/)/2.

If possible, switch to the representation using (-)/2 for better interoperability with standard library predicates (like keysort/2).


If you wish to find element with max occurrences:

occurrences([],_,0).
occurrences([X|Y],X,N):- occurrences(Y,X,W),N is W + 1.
occurrences([X|Y],Z,N):- occurrences(Y,Z,N),X\=Z.

**make_list(Max):-
   findall((Num,Elem),occurrences([d,d,d,a,a,b,c,d,e],Elem,Num),L),
   sort(L,Sorted),
   last(Sorted,(_,Max)).**
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜