man prolog/counting

Counting in Prolog: the dynamic database, assoc trees and clumped/2

lib / Prolog 9 mindraft

checked against: SWI-Prolog 11.0.1

Prolog has no mutable variables and no built-in hash map. So how do you count how often each value occurs in a list? SWI-Prolog gives you at least three answers: put the values in the database and ask it, sort the list and measure the runs, or thread a balanced tree through the list. I read the source of all three at the tag V11.0.1 of the SWI-Prolog/swipl repository and timed them on an Apple M2 Pro.

The short version

Sorting wins. msort/2 sorts in C, and clumped/2 turns the sorted list into Value-Count pairs in one pass. The database works better than it looks, because SWI-Prolog builds a hash index on a fact’s first argument the first time you look it up by that argument, so each lookup touches only the matching facts. library(assoc) is an AVL tree. Each update copies the path from the root, and since 11.0.1 that copying runs in C, which made it almost four times faster than the Prolog definition it replaces.

The database

The most Prolog way to remember something is to assert it. Each value becomes a fact, and counting a value is asking how many facts match:

:- dynamic item/1.

count_of(Key, Count) :-
    aggregate_all(count, item(Key), Count).

aggregate_all/3 lives in library(aggregate), and its count case is one call to its sum case:

aggregate_all(count, Goal, Count) :-
    !,
    aggregate_all(sum(1), Goal, Count).
aggregate_all(sum(X), Goal, Sum) :-
    !,
    State = state(0),
    (  call(Goal),
           arg(1, State, S0),
           S is S0 + X,
           nb_setarg(1, State, S),
           fail
    ;  arg(1, State, Sum)
    ).

This is a failure-driven loop. call(Goal) finds a solution, the running sum is stored in the term state(S) with nb_setarg/3, which survives backtracking, and fail sends Prolog back for the next solution. When there are no more, the second branch reads the total. The documentation above it says count, sum, max and min run in constant memory this way, without collecting the solutions with findall/3 first.

The cost is in call(Goal). With Key bound, item(Key) has to find the facts whose argument is Key among all of them. SWI-Prolog indexes just in time. The manual’s section on clause indexing says indexes are not built by the compiler or by assertz, but on the first call where an index might help. With fewer than 10 clauses it scans them; with more, it builds a hash table on an argument that is bound in the call. jiti_list/1 shows it after counting 200,000 facts:

Predicate                        #Clauses  Index  Buckets  Speedup  Coll Flags
―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
user:item/1                       200,000  1       65,536  33261.3  1283

An index on argument 1 with 65,536 buckets. Each aggregate_all call now walks one bucket instead of 200,000 clauses, so counting every distinct key this way is linear in the number of facts.

The other database style keeps one counter fact per key and replaces it:

bump(X) :-
    (   retract(counter(X, C0))
    ->  C is C0 + 1
    ;   C = 1
    ),
    assertz(counter(X, C)).

retract(counter(X, C0)) with X bound gets the same treatment: after the run, jiti_list(counter/2) reports an index on argument 1 with 65,536 buckets for 49,078 clauses.

Counting by sorting

msort/2 sorts a list and keeps duplicates, so equal values end up next to each other. Counting them is then run-length encoding, and since 8.3.17 library(lists) has a predicate for that:

?- msort([c, a, b, a, c, a], S), clumped(S, Counts).
S = [a, a, a, b, c, c],
Counts = [a-3, b-1, c-2].

The whole definition:

clumped(Items, Counts) :-
    clump(Items, Counts).

clump([], []).
clump([H|T0], [H-C|T]) :-
    ccount(T0, H, T1, 1, C),
    clump(T1, T).

ccount([H|T0], E, T, C0, C) :-
    E == H,
    !,
    C1 is C0+1,
    ccount(T0, E, T, C1, C).
ccount(List, _, List, C, C).

It counts adjacent equal elements and nothing else. On an unsorted list, clumped([a, a, b, a], C) gives [a-2, b-1, a-1], with a twice. And equal means ==, identical terms: 1 and 1.0 are different runs, so msort([1, 1.0, 1], S), clumped(S, C) gives C = [1.0-1, 1-2].

The sort is the C natural merge sort in pl-list.c that sort/2 and keysort/2 also use, O(n log n) on a shuffled list. clumped is one pass, and its result comes out sorted by value, which is often what you want next.

An AVL tree

library(assoc) stores key-value pairs in an AVL tree, a binary search tree where the heights of the two subtrees of any node differ by at most one. The tree is an ordinary Prolog term: the atom t is the empty tree, and a node is t(Key, Value, Balance, Left, Right), with Balance one of <, - or >.

?- list_to_assoc([a-1, b-2, c-3], T).
T = t(b, 2, -, t(a, 1, -, t, t), t(c, 3, -, t, t)).
              t(b, 2, -)
             /          \
     t(a, 1, -)       t(c, 3, -)
       /    \           /    \
      t      t         t      t

Keys are ordered by the standard order of terms, so any term can be a key. Counting threads the tree through the list with foldl/4:

by_assoc(Items, Counts) :-
    empty_assoc(E),
    foldl(inc, Items, E, A),
    assoc_to_list(A, Counts).

inc(X, A0, A) :-
    (   get_assoc(X, A0, C0) -> C is C0 + 1 ; C = 1 ),
    put_assoc(X, A0, C, A).

put_assoc/4 can’t change A0. It builds a new tree that shares every subtree it didn’t touch with the old one, so an update copies only the nodes on the path from the root to the key: O(log k) new nodes for k keys. The old tree stays valid and unchanged.

Until 11.0.0, put_assoc/4 was Prolog: insert/5 walks down with compare/3, and on the way back adjust/5 and a six-row table/5 decide whether the subtree grew and whether it needs a rotation. In 11.0.1 it first tries '$btree_avl_put'/4, new C code in src/pl-btree.c:

put_assoc(Key, A0, Value, A) :-
    (   '$btree_avl_put'(Key, A0, Value, A)
    ->  true
    ;   insert(A0, Key, Value, A, _)
    ).

The C version walks down once and records the path. It then knows how many nodes it will copy, so it reserves that much stack in one go, copies the nodes bottom-up and does the rotations on the copies, “which is safe because nothing else can see them yet”. It fails, and leaves the work to the Prolog code, if anything on the path is not a well-formed node, if the path is longer than AVL_MAX_DEPTH (128), or if the occurs_check flag is not false. get_assoc/3 got the same treatment: '$btree_avl_get'/3 walks the tree in C and compares two small integer keys directly, without calling the general comparison.

How fast is each

One script, 200,000 random integers from 1 to 50,000, all five ways. The fifth calls assoc:insert/5, the Prolog definition, directly, to see what the C fast path buys. get_assoc stays in C there.

:- use_module(library(random)).
:- use_module(library(statistics)).
:- use_module(library(aggregate)).
:- use_module(library(assoc)).
:- use_module(library(apply)).
:- use_module(library(lists)).
:- use_module(library(yall)).
:- initialization(main, main).

:- dynamic item/1, counter/2.

:- meta_predicate timed(+, 0).
timed(Label, Goal) :-
    garbage_collect,
    call_time(Goal, T),
    format("~w~t~32| ~1f ms~n", [Label, T.wall * 1000]).

by_database(Items, Counts) :-
    retractall(item(_)),
    forall(member(X, Items), assertz(item(X))),
    setof(X, item(X), Keys),
    findall(K-C, (member(K, Keys), aggregate_all(count, item(K), C)), Counts).

by_counter_facts(Items, Counts) :-
    retractall(counter(_, _)),
    forall(member(X, Items), bump(X)),
    findall(K-C, counter(K, C), Unsorted),
    keysort(Unsorted, Counts).
bump(X) :-
    (   retract(counter(X, C0))
    ->  C is C0 + 1
    ;   C = 1
    ),
    assertz(counter(X, C)).

by_sorting(Items, Counts) :-
    msort(Items, Sorted),
    clumped(Sorted, Counts).

by_assoc(Items, Counts) :-
    empty_assoc(E),
    foldl(inc, Items, E, A),
    assoc_to_list(A, Counts).
inc(X, A0, A) :-
    (   get_assoc(X, A0, C0) -> C is C0 + 1 ; C = 1 ),
    put_assoc(X, A0, C, A).

by_assoc_prolog(Items, Counts) :-
    empty_assoc(E),
    foldl(inc_prolog, Items, E, A),
    assoc_to_list(A, Counts).
inc_prolog(X, A0, A) :-
    (   get_assoc(X, A0, C0) -> C is C0 + 1 ; C = 1 ),
    assoc:insert(A0, X, C, A, _).

main :-
    set_random(seed(7)),
    length(Items, 200000),
    maplist([X]>>random_between(1, 50000, X), Items),
    timed('database + aggregate_all', by_database(Items, C1)),
    timed('counter facts', by_counter_facts(Items, C2)),
    timed('msort + clumped', by_sorting(Items, C3)),
    timed('assoc (C put_assoc)', by_assoc(Items, C4)),
    timed('assoc (Prolog insert)', by_assoc_prolog(Items, C5)),
    length(C3, K),
    (   C1 == C3, C2 == C3, C4 == C3, C5 == C3
    ->  format("all five agree: ~d distinct keys~n", [K])
    ;   format("MISMATCH~n")
    ),
    jiti_list(item/1),
    jiti_list(counter/2).
$ swipl count.pl
database + aggregate_all         159.0 ms
counter facts                    134.8 ms
msort + clumped                  57.7 ms
assoc (C put_assoc)              138.4 ms
assoc (Prolog insert)            529.8 ms
all five agree: 49078 distinct keys

The jiti_list tables it prints at the end are the ones quoted above. Over the ten runs I made while writing this, the database version took 151 to 185 ms, counter facts 128 to 144, sorting 53 to 58, the C put_assoc 130 to 146 and the Prolog insert 503 to 537. The order never changed. Sorting is two to three times faster than anything else. The C put_assoc is about 3.8 times faster than the Prolog one, enough to bring the tree level with the database approaches.

Curious facts

  • aggregate_all(count, G, C) is aggregate_all(sum(1), G, C). There is no separate counting code.
  • An AVL tree never gets close to AVL_MAX_DEPTH. Inserting the keys 1 to 1,000,000 in order with put_assoc/4 gives a tree of height 20, the height of a perfectly balanced binary tree with that many nodes.
  • '$btree_avl_put'/4 refuses to work when the occurs_check flag is not false, and leaves the insert to the Prolog definition.
  • Per the manual, the just-in-time index skips an argument when more than 10% of the clauses have a variable there, because those clauses must be linked into every hash bucket.
  • clumped/2 first did the sorting itself. The commit that added it on 29 December 2020 called msort/2 and documented “word frequency counting”. Five days later it was changed to match SICStus, whose clumped “implements run length encoding rather than frequency counting”. No release had the sorting version: V8.3.17 already has the new one.

History

  • 7.5.8: the manual says the search for a combination of arguments to hash on, when no single argument is good enough, was added in this version.
  • 7.7.4: deep indexing, on the arguments of compound terms, according to the manual.
  • 8.3.17: clumped/2 appears in library(lists). The commit “ADDED: clumped/2 to library(lists)” is dated 29 December 2020, and V8.3.17 is the first tag whose lists.pl contains it.
  • 9.3.18: per the manual, the last version where the primary index was always the first argument. Later versions use the first argument for which at least one clause has a value.
  • 11.0.1 (tagged 24 November 2026): put_assoc/4 and get_assoc/3 run in C. The commits “ENHANCED: put_assoc/4: insert and update implemented in C” and “ENHANCED: get_assoc/3: lookup implemented in C” are dated 18 and 20 November 2026 and are among those between the tags V11.0.0 and V11.0.1.

Sources

ls prolog/

  • draft Sorting in Prolog: standard order of terms, msort and sort/4How SWI-Prolog 11.0.1 sorts: the standard order of terms that lets sort/2 work without a comparison, the natural merge sort in pl-list.c behind sort/2, msort/2, keysort/2 and sort/4, and the two ways a sort can quietly drop your data.