# Prolog – 在列表中统计重复次数

``count_repetitions([_], [], 0). count_repetitions([Word], [Word|Tail], Count):- count_repetitions([Word], Tail, X), Count is X + 1. count_repetitions([Word], [Z|Tail], Count):- Word \= Z, count_repetitions([Word], Tail, Count).` `

` `word_repetitions(Word, List, [(Word-Count)]) :- count_repetitions(Word, List, Count).` `

` `word_repetitions(Word, List, Word-Count) :- count_repetitions(Word, List, Count).` `

（但如果你坚持，你可以使用它们）。

` `list_word_reps([], Word, Word-0). list_word_reps([W|Rest], Word, Word-Reps) :- list_word_reps(Rest, Word, Word-Reps0), ( W == Word -> Reps is Reps0 + 1 ; Reps = Reps0 ). ?- list_word_reps([yes,no,yes,no,maybe,yes], yes, X). X = yes-3.` `

` `:- use_module(library(clpfd)).` `

` `:- meta_predicate tcount(2,?,?). tcount(P_2,Xs,N) :- N #>= 0, list_pred_tcount_(Xs,P_2,0,N). :- meta_predicate list_pred_tcount_(?,2,?,?). list_pred_tcount_([] , _ ,N ,N). list_pred_tcount_([X|Xs],P_2,N0,N) :- if_(call(P_2,X), (N1 is N0+1, N1 #=< N), N1 = N0), list_pred_tcount_(Xs,P_2,N1,N).` `

` `?- tcount(=(yes),[yes,and,yes,and,no],Count). Count = 2.` `

` `?- tcount(=(yes),[A,B,C,D],2). A=yes , B=yes , dif(C,yes), dif(D,yes) ; A=yes , dif(B,yes), C=yes , dif(D,yes) ; A=yes , dif(B,yes), dif(C,yes), D=yes ; dif(A,yes), B=yes , C=yes , dif(D,yes) ; dif(A,yes), B=yes , dif(C,yes), D=yes ; dif(A,yes), dif(B,yes), C=yes , D=yes ; false.` `

` `?- tcount(=(yes),[A,B,C,D],Count). A=yes , B=yes , C=yes , D=yes , Count = 4 ; A=yes , B=yes , C=yes , dif(D,yes), Count = 3 ; A=yes , B=yes , dif(C,yes), D=yes , Count = 3 ; A=yes , B=yes , dif(C,yes), dif(D,yes), Count = 2 ; A=yes , dif(B,yes), C=yes , D=yes , Count = 3 ; A=yes , dif(B,yes), C=yes , dif(D,yes), Count = 2 ; A=yes , dif(B,yes), dif(C,yes), D=yes , Count = 2 ; A=yes , dif(B,yes), dif(C,yes), dif(D,yes), Count = 1 ; dif(A,yes), B=yes , C=yes , D=yes , Count = 3 ; dif(A,yes), B=yes , C=yes , dif(D,yes), Count = 2 ; dif(A,yes), B=yes , dif(C,yes), D=yes , Count = 2 ; dif(A,yes), B=yes , dif(C,yes), dif(D,yes), Count = 1 ; dif(A,yes), dif(B,yes), C=yes , D=yes , Count = 2 ; dif(A,yes), dif(B,yes), C=yes , dif(D,yes), Count = 1 ; dif(A,yes), dif(B,yes), dif(C,yes), D=yes , Count = 1 ; dif(A,yes), dif(B,yes), dif(C,yes), dif(D,yes), Count = 0.` `

` `?- tcount(_,_,-1). false.` `

``` 1 ... 3中的N， 长度 （Xs，N）。
N = 1，Xs = [_A]
;  N = 2，Xs = [_A，_B]
;  N = 3，Xs = [_A，_B，_C]
...％ 不会终止

？ -  use_module（library（lambda））。

N = 1..3， tcount （\ _ ^ =（true），Xs，N）。
N = 1，Xs = [_A]
;  N = 2，Xs = [_A，_B]
;  N = 3，Xs = [_A，_B，_C]
;  假。  ％ 终止普遍
```

` `count(L, C) :- aggregate(set(WN), aggregate(count, member(W, L), N), C).` `

` `1 ?- count([a,b,a],C). C = [a-2, b-1].` `

` `count(W, L, WN) :- aggregate(count, member(W, L), N).` `

` `?- count(a, [a,b,a], C). C = a-2.` `