1

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

repeat
  • 18,496
  • 4
  • 54
  • 166
ohyeah
  • 101
  • 1
  • 2
  • 3

4 Answers4

2

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
  • 2,350
  • 14
  • 25
  • 2
    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 Dec 12 '09 at 07:47
  • Preserve [tag:logical-purity] by using `dif/2` instead of `(\==)/2`! More info on `dif` is here: [tag:prolog-dif] – repeat Oct 07 '15 at 02:05
1

Use the tcount/3 in tandem with reified term equality (=)/3 like this:

?- tcount(=(hello),[hello,how,are,you,hello,hello],N).
N = 3.                          % succeeds deterministically
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
-1

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

An even better aswer

countWord([],0).
countWord([_|List], A):- countWord(List,B), A is B+1.
alaboudi
  • 3,187
  • 4
  • 29
  • 47