man prolog/sorting
Sorting in Prolog: standard order of terms, msort and sort/4
sort/2 in Prolog takes a list of anything and returns it sorted, with
duplicates removed. You don’t pass a comparison. Numbers, atoms, strings and
compound terms can share one list. What order does it use, what algorithm is
behind it, and how do you sort pairs by their second element, largest first?
?- sort([f(x), "text", atom, 2, 1.0, 1, g(a, b), 0.5, atom], L).
L = [0.5, 1.0, 1, 2, "text", atom, f(x), g(a, b)].
This article reads the source of SWI-Prolog at the tag V11.0.1, the version
Homebrew installs, and checks it with small scripts run on an Apple M2 Pro.
The tag lives in the SWI-Prolog/swipl repository; swipl-devel has no
V11.0.1 tag.
The short version
Prolog defines a standard order over all terms, so any two terms can be
compared with compare/3 or @<. sort/2, msort/2, keysort/2 and
sort/4 are one C function in src/pl-list.c, a natural merge sort on a
linked list contributed by Richard O’Keefe, called with different flags:
remove duplicates or not, ascending or descending, compare the whole term or
one argument of it. sort/2 and keysort/2 are ISO; msort/2 and sort/4
are SWI-Prolog’s. predsort/3, the one that takes your own comparison, is
written in Prolog in library(sort) and is ten times slower.
The standard order of terms
The SWI-Prolog manual defines the order like this:
Var < Number < String < Atom < Compound
Variables are ordered by address. Numbers compare by value, and when a float and an integer are equal, the float comes first. Strings and atoms compare alphabetically. Compound terms compare by arity first, then by name, then by their arguments from left to right.
A script that sorts one of each, without removing duplicates:
:- initialization(main, main).
main :-
msort([f(x), "text", atom, 2, 1.0, 1, _, g(a, b), [1], 0.5], L1),
print(L1), nl,
msort([b(1, 2), a(9, 9, 9), z(0)], L2),
print(L2), nl,
set_prolog_flag(iso, true),
msort([1, 0.5, 2.0, 3], L3),
print(L3), nl.
$ swipl order.pl
[_2796,0.5,1.0,1,2,"text",atom,f(x),[1],g(a,b)]
[z(0),b(1,2),a(9,9,9)]
[0.5,2.0,1,3]
1.0 sorts before 1. z(0) sorts first because it has one argument,
whatever its name. [1] sorts before g(a, b) because a list cell is a
compound with two arguments whose name, '[|]', sorts before g. The third
line shows what changes with the iso flag: the manual says that then all
floats precede all integers, so 2.0 lands before 1.
Strings come before atoms. I expected the opposite, but the manual at the tag
lists strings first, and so did the manual for 9.2.9. Strings are a separate
type in SWI-Prolog: the double_quotes flag is string by default, so
"text" is a string object rather than a list of character codes.
In the C code the order falls out of the tag bits. Every term is a word
whose low three bits (tag(w) is w & 7) say what it is, and src/pl-data.h numbers them:
TAG_VAR 0 TAG_INTEGER 3 TAG_COMPOUND 6
TAG_ATTVAR 1 TAG_STRING 4
TAG_FLOAT 2 TAG_ATOM 5
compare_primitives() in src/pl-prims.c first handles a float against an
integer, comparing their values unless the iso flag is set. For any other
two terms with different tags it returns t1 < t2 ? CMPEX_LESS : CMPEX_GREATER. The type order is the tag order. Only when the tags are equal
does it look inside: two small integers are compared as machine words, and
two compounds go to compare_functors(), which checks the arity before the
name.
Five ways to sort
predicate ISO duplicates compares where
sort/2 yes removed whole term C, pl-list.c
msort/2 no kept whole term C, pl-list.c
keysort/2 yes kept key of K-V C, pl-list.c
sort/4 no you choose an argument C, pl-list.c
predsort/3 no removed your predicate Prolog, library(sort)
The first four end in the same call. At the bottom of pl-list.c,
sort/2 is pl_nat_sort(A1, A2, true, SORT_ASC, 0, NULL, false): remove
duplicates, ascending, no key, not pairs. msort/2 passes false for
duplicates and keysort/2 passes true for pairs. sort/4 turns its order
atom into those two flags with a table:
@< ascending remove
@=< ascending keep
@> descending remove
@>= descending keep
The plain <, =<, > and >= are accepted as synonyms, for ECLiPSe,
whose sort/4 SWI-Prolog’s was designed to match. The key is 0 for the
whole term, an argument number, a dict key, or a list of those to reach
deeper into a term.
Inside the merge sort
pl_nat_sort() first walks the input list and builds a linked list of
records on top of Prolog’s global stack, three words each:
+--------+--------+--------+
| next | term | key |
+--------+--------+--------+
term points at the element and key at the part being compared: the whole
term, the key of a pair, or the argument sort/4 asked for. Then
nat_sort() takes runs off the front of this list. A run starts with two
records, swapped if they are out of order, and grows while the next record
is not smaller than the last. Each run is pushed on a stack of 64 entries,
and merged with the top of the stack as many times as the run count has
trailing zero bits: the second run merges with the first, the fourth with
the merged pair, and so on, like a binary counter. At the end, whatever is
left on the stack is merged.
Duplicates are dropped inside this loop. When removal is on and two records
compare equal, the later one is unlinked. Descending order is one line in
the compare macro: if ( order == SORT_DESC ) c = -c. Equal records still
compare as 0, and the merge takes from the earlier run when the result is
c <= 0, so the sort stays stable in both directions.
The last step reuses the memory. A list cell in SWI-Prolog is also three
words: the functor '[|]'/2, the head and the tail. put_sort_list()
rewrites each record in place into a list cell, in sorted order, and moves
the top of the global stack to just past them. The sort allocates three words
per element, and those words become the result list. A removed duplicate
leaves its three words behind as garbage.
The comment above the code promises O(N) on a list that is already sorted. On a list in reverse order every run is two elements long, but each merge stops comparing as soon as one side runs out, and here that is always after one side’s length. A script that sorts a million integers three ways:
:- use_module(library(random)).
:- use_module(library(statistics)).
:- initialization(main, main).
ms(Goal, Ms) :-
garbage_collect,
call_time(Goal, T),
Ms is round(T.wall * 1000).
main :-
numlist(1, 1000000, Ascending),
reverse(Ascending, Descending),
set_random(seed(42)),
random_permutation(Ascending, Shuffled),
ms(msort(Ascending, _), T1),
ms(msort(Descending, _), T2),
ms(msort(Shuffled, _), T3),
format("ascending ~d ms, descending ~d ms, shuffled ~d ms~n", [T1, T2, T3]).
$ swipl runs.pl
ascending 11 ms, descending 80 ms, shuffled 419 ms
Over six runs on a machine that was sometimes busy with other work, the numbers ranged over 10 to 11, 76 to 84, and 330 to 482 ms. A sorted list is one run and costs a single pass.
Sorting by one field
The classic way to sort pairs by their value is to swap them to
Value-Key, keysort them, and reverse the result if you want the largest
first. library(pairs) packages the first two as transpose_pairs/2, which
is exactly flip_pairs followed by keysort. sort/4 does it in one call.
And predsort/3 takes a comparison predicate. Timing all four on 200,000
pairs with random values from 1 to 1000, best of five calls each:
:- use_module(library(random)).
:- use_module(library(statistics)).
:- use_module(library(pairs)).
:- use_module(library(yall)).
:- initialization(main, main).
:- meta_predicate best(0, -).
best(Goal, Ms) :-
findall(T, ( between(1, 5, _), garbage_collect,
call_time(Goal, D), T is D.wall * 1000 ), Ts),
min_list(Ts, Ms).
flip(K-V, V-K).
by_value_desc(Order, _-A, _-B) :-
compare(O, B, A),
( O == (=) -> Order = (<) ; Order = O ).
main :-
set_random(seed(1)),
numlist(1, 200000, Keys),
maplist([K, K-V]>>random_between(1, 1000, V), Keys, Pairs),
best(sort(2, @>=, Pairs, _), T1),
best((transpose_pairs(Pairs, A), reverse(A, _)), T2),
best((maplist(flip, Pairs, F), keysort(F, S), reverse(S, _)), T3),
best(predsort(by_value_desc, Pairs, _), T4),
format("sort/4 ~1f ms~n", [T1]),
format("transpose_pairs + reverse ~1f ms~n", [T2]),
format("flip + keysort + reverse ~1f ms~n", [T3]),
format("predsort ~1f ms~n", [T4]).
$ swipl rank.pl
sort/4 46.4 ms
transpose_pairs + reverse 56.8 ms
flip + keysort + reverse 61.7 ms
predsort 477.9 ms
Over six runs sort/4 took 36 to 47 ms and predsort 466 to 520 ms, and
the order of the four never changed. predsort is a top-down merge sort written in Prolog that calls your
predicate for every comparison, and that costs ten times more. The two
keysort versions add passes written in Prolog: one to swap the pairs and
one to reverse the result.
The keysort versions also order ties differently. keysort is stable, so
pairs with the same value stay in input order, and reverse then flips that
order. sort(2, @>=, ...) keeps ties in input order. If the input was in key
order, one gives the largest key first among ties and the other the
smallest.
Two ways to lose data
by_value_desc above turns = into <, and that line matters. The
manual says predsort/3 removes duplicates, where a duplicate is anything
your predicate calls =. If you compare only the values, every pair with an
equal value but a different key is gone. sort/4 with a strict order does
the same, and there a duplicate means an equal key:
:- use_module(library(yall)).
:- initialization(main, main).
main :-
Pairs = [apple-3, fig-1, kiwi-3, pear-2, plum-1],
sort(2, @>=, Pairs, A), print(A), nl,
sort(2, @>, Pairs, B), print(B), nl,
sort(2, @=<, Pairs, C), print(C), nl,
sort(2, @<, Pairs, D), print(D), nl,
sort(0, @>=, [c, a, b, a], E), print(E), nl,
predsort([O, _-X, _-Y]>>compare(O, Y, X), Pairs, F), print(F), nl.
$ swipl sort4.pl
[apple-3,kiwi-3,pear-2,fig-1,plum-1]
[apple-3,pear-2,fig-1]
[fig-1,plum-1,pear-2,apple-3,kiwi-3]
[fig-1,pear-2,apple-3]
[c,b,a,a]
[apple-3,pear-2,fig-1]
With @> and @<, kiwi and plum disappear. The manual says that when
duplicates are removed, the first of each group stays. For “sort by this
field”, the order you almost always want is @>= or @=<.
Curious facts
sort/2accepts a cyclic list.L = [b, a, c|L], sort(L, S)givesS = [a, b, c], because removing duplicates makes the result finite.msort/2on the same list raises a type error. The check is one line inprolog_list_to_sort_list(): a list whose tail loops back is allowed only when duplicates are removed.sort([1, 1.0], L)keeps both and gives[1.0, 1]. They are equal by value but not equal in the standard order, so neither is a duplicate.- A list of one element is returned without sorting, except by
keysortand bysort/4with a key, which still look at the element.msort([a], L)gives[a]andkeysort([a], L)raisestype_error(pair, a). - The C sort has room for 64 runs on its stack, and the comment says “enough for biggest machine”. Because runs merge like a binary counter, the stack holds at most one run per bit of the run count.
- The comment in
pl-list.ccredits Richard O’Keefe and says he had used a variant of the code in a sorting utility “since about 1988”.
History
- 7.1.34 (development release, 2015):
sort/4arrives. The commit “Generalise sorting primitives to accommodate ECLiPSe sort/4” is dated 28 March 2015, and the tagV7.1.34is the first withsort/4inpl-list.c. Support for dicts followed the next day. - 9.1.4: the manual’s footnote says that up to this version a float and
an integer were compared as floats. Since then they are compared with
cmpr/2. - 11.0.1 (tagged 24 November 2026): the version read for this article. The standard order at this tag puts strings before atoms, as the manual has said since at least 9.2.9.
Sources
src/pl-list.cat V11.0.1: the natural merge sort comment,comparemacro and descending order,nat_sort(),prolog_list_to_sort_list(),put_sort_list(),sort/2,msort/2,keysort/2,sort/4and its order tablesrc/pl-prims.c,compare_primitives()andcompare_functors()src/pl-data.h, the tagslibrary/sort.pl,predsort/3library/pairs.pl,transpose_pairs/2- Manual source at V11.0.1:
Standard Order of Terms,
sort/4,msort/2,keysort/2,predsort/3 - SWI-Prolog manual, Standard Order of Terms
and
sort/4 - Commit 7347f817a4, “Generalise sorting primitives to accommodate ECLiPSe sort/4”
man/builtin.docat V9.2.9, for the order of strings and atoms in an older manual
grep -rl /lib/prolog/sorting/
ls prolog/
- draft Counting in Prolog: the dynamic database, assoc trees and clumped/2Three ways to count occurrences in SWI-Prolog 11.0.1, what each does inside (just-in-time hash indexes, a failure-driven loop, a sort, an AVL tree with a brand-new C fast path), and how fast each one is.