How to count the number of entries in a list in Prolog

im new in the prologue, so the question may be easy for you, but I could not find the answer. Can someone please help me.

I just want to

account function st

count([c,c,a,a,b,b,d,a,c,b,d,d,a], O). 

it will return the number of occurrences of the list items.

  O = [[a, 4], [b, 3], [c, 3], [d, 3]] 
+1
source share
2 answers

Below is my previous answer to " Delete Duplicates in the List (Prolog) " and to this previous answer to the question " Union Prolog for AUBUC ".

list_item_subtracted_count0_count/5 is derived from list_item_subtracted/3 . list_counts/2 obtained from list_setB/2 , which were defined as here .

<Preview> list_item_subtracted_count0_count ([], _, [], N, N). list_item_subtracted_count0_count ([A | As], E, Bs1, N0, N): - if_ (A = E, (Bs1 = Bs, N1 is N0 + 1), (Bs1 = [A | Bs], N1 = N0)) , list_item_subtracted_count0_count (As, E, Bs, N1, N). list_counts ([], []). list_counts ([X | Xs], [XN | Ys]): - list_item_subtracted_count0_count (Xs, X, Xs0, 1, N), list_counts (Xs0, Ys).

Here the OP query gave:

 ?- list_counts([c,c,a,a,b,b,d,a,c,b,d,d,a], Xss). Xss = [c-3,a-4,b-3,d-3]. % succeeds deterministically 

Note that the order of the XN pairs in Counts corresponds to the first occurrence of X in Xs :

  ? - list_counts ([ a , b, c, d], Xss).
 Xss = [ a -1, b-1, c-1, d-1].

 ? - list_counts ([d, c, b, a ], Xss).
 Xss = [d-1, c-1, b-1, a -1].

Finally, consider all of the possible Es lists - fairly listed with increasing lengths:

<Preview>? - length (Es, N), list_counts (Es, Xss). N = 0, Es = [], Xss = []; N = 1, Es = [A], Xss = [A-1]; N = 2, Es = [A, A], Xss = [A-2]; N = 2, Es = [A, B], Xss = [A-1, B-1], dif (B, A); N = 3, Es = [A, A, A], Xss = [A-3]; N = 3, Es = [A, A, B], Xss = [A-2, B-1], dif (B, A); N = 3, Es = [A, B, A], Xss = [A-2, B-1], dif (B, A); N = 3, Es = [B, A, A], Xss = [B-1, A-2], dif (A, B), dif (A, B); N = 3, Es = [A, B, C], Xss = [A-1, B-1, C-1], dif (C, A), dif (C, B), dif (B, A) ...
+2
source
 co(X,L) :- co(X,[],L). co([],A,A). co([X|Xs], A, L) :- p(XZ,A,R), !, Z1 is Z+1, co(Xs, [X-Z1|R], L). co([X|Xs], A, L) :- co(Xs, [X-1|A], L). p(XY,[XY|R],R):- !. p(X,[H|Y], [H|Z]) :- p(X,Y,Z). 

I specifically did not use very meaningful names. Try to understand what each predicate does.

0
source

All Articles