I want to count the occurrences of an item in a list

I want to count the occurrences of an element in the list, and if there is one, then the unique predicate will be true, otherwise false. However, if an element occurs more than once, Prolog finds it true. I do not know what to do...

count([], X, 0).
count([X|T], X, Y) :- count(T, X, Z), Y is 1+Z, write(Z).
count([_|T], X, Z) :- count(T, X, Z).

unique(St, [Y|RestList]) :- count([Y|RestList], St, N), N =:= 1.
+3
source share
2 answers

The solution works because the first argument is the main list. In some other cases this is not true:

?- count([E], a, 0).
false.

Here we ask

How should an element of a Elist of length 1 look so that the list contains 0 entries a?

And actually there are answers to this, for example, E = bor E = c:

?- count([b],a,0).
true.

?- count([c],a,0).
true.

. , . ?

count([], _, 0).
count([E|Es], F, N0) :-
   count(Es, F, N1),
   if_(E = F, D = 1, D = 0),
   N0 is N1+D.

if_/3 (=)/3.

?- length(Xs, I), count_dif(Xs, a, N).
   Xs = [],
   I = N, N = 0
;  Xs = [a],
   I = N, N = 1
;  Xs = [_A],
   I = 1,
   N = 0,
   dif(_A, a)
;  Xs = [a, a],
   I = N, N = 2
;  Xs = [_A, a],
   I = 2,
   N = 1,
   dif(_A, a) ;
   Xs = [a, _A],
   I = 2,
   N = 1,
   dif(_A, a) ;
   Xs = [_A, _B],
   I = 2,
   N = 0,
   dif(_A, a),
   dif(_B, a)
...

, library(clpfd), SICStus, YAP SWI.

:- use_module(library(clpfd)).

count([], _, 0).
count([E|Es], F, N0) :-
   N0 #>= 0,
   if_(E = F, D = 1, D = 0),
   N0 #= N1+D,
   count(Es, F, N1).

:

?- count([a,a|_], a, 1).
false.

?- N #< 2, count([a,a|_], a, N).
false.
+4

, :

  • count
  • .

:

count([],_,0).

count([X|T],X,Y):- !, count(T,X,Z), Y is 1+Z.

count([_|T],X,Z):- count(T,X,Z).

unique(St,L):- count(L,St,1).

:

?- count([2,3,4,3], 3,N).
N = 2.

?- unique(3, [2,3,4,5]).
true.
+1

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


All Articles