Prolog中的Python计数器

S0r*_*rin 0 prolog

在Python中你可以做到

>>> import from collections counter
>>> Counter(['a','b','b','c'])
>>> Counter({'b': 2, 'a': 1, 'c': 1})
Run Code Online (Sandbox Code Playgroud)

Prolog有类似的东西吗?像这样:

counter([a,b,b,c],S). 
S=[a/1,b/2,c/1].
Run Code Online (Sandbox Code Playgroud)

这是我的实施:

counter([],List,Counts,Counts).

counter([H|T],List,Counts0,[H/N|Counts]):-
  findall(H, member(H,List), S),
  length(S,N),
  counter(T,List,Counts0,Counts).

counter(List,Counts):-
  list_to_set(List,Set),
  counter(Set,List,[],Counts).
Run Code Online (Sandbox Code Playgroud)

它相当冗长,所以我想知道是否有内置谓词或更简洁的实现.

joe*_*l76 5

没有内置谓词,这是另一种方法:

counter([X], [X/1]).

counter([H | T], R) :-
    counter(T, R1),
    (   select(H/V, R1, R2)
    ->  V1 is V+1,
        R = [H/V1 | R2]
    ;   R = [H/1 | R1]).
Run Code Online (Sandbox Code Playgroud)