1

I'm trying to define a predicate count(Word,List,N) which is true when N is the number of times that the word Word occurs in list List. For example

    count(my, [the, friend, of, my, enemy, is, not, my,enemy,nor,my,friend], N)

should be true for N = 3.

The following is what I tried so far:

count(Word, [], 0). 
count(Word, [Word|Tail], N) :-
    count(Word, Tail, NofTail), N is 1 + NofTail.
count(Word, [OtherWord|Tail], NofTail) :-
    OtherWord \= Word, count(Word, Tail, NofTail).

When I tried it in RPEL:

?- count(s,[s,z],1).
true ;
false. %note here

?- count(s, [s,s,s,z], 3).
true ;
false. %note here

?- count(s, [s,s,s,z], 1).
false.

Am I doing right? If not, why? How to fix it?

Yue Wang
  • 1,710
  • 3
  • 18
  • 43
  • 3
    You get the correct solution: `true`. The `; false` only means that there are no remaining alternatives. Other than that, use `dif/2` instead of `(\=)/2`, and CLP(FD) constraints instead of low-level arithmetic to make your predicate much more general. Try for example: `?- count(Word, Ls, N).`, which will work as expected if you just use more relational predicates. – mat Aug 08 '15 at 07:00
  • 2
    Please look at [this answer](http://stackoverflow.com/a/29960878/772868) – false Aug 08 '15 at 07:54

0 Answers0