Prolog - checking the number of entries does not work properly

In Prolog: I have the following function that takes into account the occurrence of an element in a list:

%count(L:list,E:int,N:int) (i,i,o)
count([],_,0).
count([H|T],E,C):-H == E,count(T,E,C1),C is C1+1.
count([_|T],E,C):-count(T,E,C).

I tested it and it works well. But here a problem arises, I have another function that should check that "1" is found less than 2 times in the list.

check(L):-count(L,1,C),C<2.

Whenever I try to check a list [1,1,1,1], for example, the result I get is “true”, which is wrong and I have no idea why. I tried to make some changes, but the function just won't work.

+4
source share
3 answers

, count([1,1,1,1],1,1) ! count , H E. , ;, count([1,1,1,1],1,R). , .

count([],_,0).
count([E|T],E,C):-
    count(T,E,C1),
    C is C1+1.
count([H|T],E,C):-
    H \= E,
    count(T,E,C).

check(L) :- 
    count(L,1,C),
    C < 2.


?- check([1,1,1,1,1]).
false
?- check([1]).
true
+1

!

Prolog - " ".

Prolog.

- ( ), ( / ) .


... / logical-purity, @Ruben, :

count([],_,0).
count([E|T],E,C) :-
   count(T,E,C1),
   C is C1+1.
count([H|T],E,C) :- 
   dif(H,E),
   count(T,E,C).

dif/2 . . !

+3

the chapters of the second and third clutches correspond to the same sequence. As a minimum correction, I would run a test

count([],_,0).
count([H|T],E,C):-H == E,!,count(T,E,C1),C is C1+1.
count([_|T],E,C):-count(T,E,C).
0
source

Source: https://habr.com/ru/post/1616547/


All Articles