ISO-Prolog provides sort/2
and keysort/2
which relies on term order (7.2) often called "standard term order".
The common way to sort a list with a different order is to map each element El
of that list somehow to a list of pairs XKey-El
and then sort that list, and finally project the keys away. As an example consider how keysort/2
can be expressed in terms of sort/2
(See the note for an implementation).
In many situations this approach is much faster than using a generic implementation specific sorting predicate that relies on a user defined order as SWI's predsort(C_3, List, SortedList)
or SICStus' samsort(O_2, List, SortedList)
.
My question boils down to:
Are there cases where a sorting using
predsort/3
resp.samsort/3
cannot be replaced by some mapping,sort/2
-ing and projecting?1
And for the sake of clarity, better stick to finite, ground terms. For, infinite ground terms do no possess a total, lexicographic order as it would be needed as an extension of the finite case ; and further, it is not clear how the comparison of variables with the case of two different variables being implementation dependent will turn out given 7.2.1 of ISO/IEC 13211-1:1995:
7.2.1 Variable
If
X
andY
are variables which are not identical thenX
term_precedesY
shall be implementation dependent
except that during the creation of a sorted list (7.1.6.5,
8.10.3.1 j) the ordering shall remain constant.
So it is not clear whether predsort/3
would still qualify as a
creation of a sorted list. What is clear is that the ordering remains constant during sort/2
and keysort/2
.
1 Thanks to @WillNess, this projection should at least include also reverse/2
— or any linear transformation. It also means that results with both duplicates and unique ones can be implemented (similarly to the way keysort/2
is implemented).
predsort
will give different results depending on the initial input order. – Eugene Sh.keysort
will also give different results on permutations of a list with equivalent elements, as inkeysort([a-b,a-c], Sorted)
vs.keysort([a-c,a-b], Sorted)
, even though equivalence is transitive. – user1812457predsort/3
! So you will get quasi-random results with it. Compared to that the other approach will give similarly random results. – false