Prolog: fixing multiple answers (using cut?)

I am counting the number of instances in the list ...

count(_,[],N,N).
count(Elem,[Elem|List],N,M) :- !, N1 is N+1, count(Elem,List,N1,M). 
count(Elem,[_|List],N,M) :- count(Elem,List,N,M). 

So, I wrote this two paths in the prologue, and the first one works (above), but I was curious to find out why the second one does not (more precisely, will give me several answers - only the first one is correct) why is this?

many thanks

count(Z,X,R) :- count2(Z,X,R,0).
count2(W,[H|T],L,A):- (W == H), Lnew is A+1, count2(W,T,L,Lnew).
count2(W,[H|T],L,A):- count2(W,T,L,A).
count2(W,[],A,A).
+5
source share
3 answers

The reason your second attempt creates multiple solutions is because the second count2 clause does not prevent W and H from accepting the same values. Therefore, even if the first sentence of count2 succeeds, it can go back and execute the second sentence again.

, , , , , W H, :

count(Z,X,R) :- count2(Z,X,R,0).
count2(W,[W|T],L,A):- Lnew is A+1, count2(W,T,L,Lnew).
count2(W,[H|T],L,A):- W \= H, count2(W,T,L,A).
count2(_,[],A,A).

, count2 . . , . , , , , .

+2

... . "" . , .

, . . , , . , . , , .

0

got it!

here is a solution that works:

count(Z,X,R) :- count2(Z,X,R,0).
count2(W,[H|T],L,A):- (W == H), !, Lnew is A+1, count2(W,T,L,Lnew).
count2(W,[H|T],L,A):- count2(W,T,L,A).
count2(W,[],A,A).

Thanks, Vincent, you made me go back to the cut!

-1
source

All Articles