count_occurrences



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

.



Relevant Pages

  • Re: count_occurrences
    ... in Michael Covington's book entitled "Programming Prolog in Depth". ... instantiates N to the number of times that element X occurs in list L: ... The number of times X occurs in the list which has first element X is ...
    (comp.lang.prolog)
  • Re: count_occurrences
    ... in Michael Covington's book entitled "Programming Prolog in Depth". ... instantiates N to the number of times that element X occurs in list L: ... The number of times X occurs in the list which has first element X is ...
    (comp.lang.prolog)