Disclaimer: I seem to have a preoccupation with ordering and sorting; I have managed to not let it influence my daily life too badly. I lived in Germany once but I left the country.
This topic pops up periodically. This time it is the library(ordsets) and multisets discussion. This is not an exclusive list.
Back from 2015, when discussing the then new library(solution_sequences), on the old forum:
On 02/13/2015 02:54 PM, Boris Vassilev wrote:
On Fri, Feb 13, 2015 at 3:45 PM, Jan Wielemaker <J.Wielemaker@vu.nl
mailto:[J.Wielemaker@vu.nl](mailto:J.Wielemaker@vu.nl)> wrote:As defined, predsort/3 removes duplicates, so stable has no meaning …
You can trick it into doing a stable sort. Just unify Delta with
<
when the keys are equivalent, instead of=. This relies on predsort/3
keeping the original order of pairs of elements when comparing them. The
current implementation of predsort/3 does that, but of course this is
not a requirement, so I know it should not be done.Didn’t know that
Cheers — Jan
I provided the trivial solution in this post:
equivalence_compare(Order, X, Y) :-
compare(Order0, X, Y),
( Order0 == '='
-> Order = '<'
; Order0 = Order
).
At that time I had accepted that keeping the original order of equivalent elements is not in the specification of predsort/3. The following still holds true:
- The predsort/3 implementation uses a merge sort.
- A merge sort can be made stable in respect to the order of the input list without any additional logic (just don’t swap the order of the inputs unnecessarily).
- In Prolog (and for linked lists in general), merge sort is a better algorithm than for example quicksort (which is not stable).
Both sets and multisets have a well-defined representation as a sorted list; the difference is whether it is the result of sort/2 (set) or msort/2 (multiset).
Right now I suspect that the widely accepted, “textbook” algorithms that work on Prolog “sets” are by definition correct also for “multisets”. It will take me some days or weeks to convince myself that this is true.
I am posting this in the hope that someone on the forum already knows that as a fact and can provide a proof, for example in the form of a reference to an external source; or correct my misunderstanding.
I am definitely not suggesting to change the spec or implementation of any library predicate.