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
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
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).
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).
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.