tags:

views:

126

answers:

3

How to count how many times of a WORD occurs in a List?

For example: counthowmany(hello,[hello,how,are,you,hello,hello],N).

N gives the total number of word 'hello' occurs

Thanks

+2  A: 

Here is a solution:

counthowmany(_, [], 0) :- !.
counthowmany(X, [X|Q], N) :- !, counthowmany(X, Q, N1), N is N1+1.
counthowmany(X, [_|Q], N) :- counthowmany(X, Q, N).

The first line is the termination test: on an empty list, the count is zero. The two other lines are the recursive calls, and if the first element matches (line 2), the count is incremented.

Here is a similar but purely logical version (no cut), as suggested by Darius:

counthowmany(_, [], 0).
counthowmany(X, [X|Q], N) :- counthowmany(X, Q, N1), N is N1+1.
counthowmany(X, [Y|Q], N) :- X \== Y, counthowmany(X, Q, N).
Jerome
I would've written it without any cuts, using a not-equals test in the last clause instead, since purely-logical definitions are less error-prone to use.
Darius Bacon
A: 

Here is an alternate implementation. This is Tail recursive using accumulators.

countwords(X,L,N) :- countwords(X,L,0,N),!.
countwords(X,[],N,N).
countwords(X,[X|T],P,N) :- P1 is P+1 , countwords(X,T,P1,N).
countwords(X,[H|T],P,N) :- X\==H , countwords(X,T,P,N).
bakore
A: 

C# using Linq

var words = new[] { "hello","how","are","you","hello","hello" };
var helloCount = words.Where(word => word == "hello").Count();

(replace word == "hello" with word.ToLower() == "hello" if you need to ignore case.

Will
Isn't it a little irrelevant to post a C# answer for Prolog question?..
Regent
Oops, I didn't spot any particular language at the time I posted this. My bad! =)
Will