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).
Use the meta-predicate tcount/3
in tandem with reified term equality (=)/3
like this:
?- tcount(=(hello),[hello,how,are,you,hello,hello],N).
N = 3. % succeeds deterministically
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).
An even better aswer
countWord([],0).
countWord([_|List], A):- countWord(List,B), A is B+1.