count_occurrences
- From: phiroc@xxxxxxx
- Date: Thu, 11 Oct 2007 01:07:25 -0700
As a learning exercise, I have been trying to do exercise 3.8.1
in Michael Covington's book entitled "Programming Prolog in Depth".
The exercise requires "defin[ing] a predicate count_occurrences(X,L,N)
that
instantiates N to the number of times that element X occurs in list L:
? count_occurrences(a,[a,b,c,a,d,a], What).
What = 5"
Here's my implementation:
listlen(L, N) :- lenacc(L, 0, N).
lenacc([], A, A).
lenacc([_|T], A, N) :- A1 is A + 1, lenacc(T, A1, N).
co(X,[X|_],1).
co(X,[_ | Tail], N) :- co(X, Tail, M), N is M.
count_occurrences( A, List, What ) :-
findall(B, co(A,List,B),List1), listlen(List1, What).
Is there a more efficient way of doing this?
Many thanks.
phiroc
.
- Follow-Ups:
- Re: count_occurrences
- From: Matthew Huntbach
- Re: count_occurrences
- Prev by Date: Re: creating groups
- Next by Date: Re: count_occurrences
- Previous by thread: creating groups
- Next by thread: Re: count_occurrences
- Index(es):
Relevant Pages
|
|