From ddcfc81ff1fe01e4ab74cec80709cac8f77361d5 Mon Sep 17 00:00:00 2001 From: Sergei Zimmerman Date: Sun, 15 Jun 2025 16:51:42 +0000 Subject: [PATCH] libexpr: Document requirements for comparator passed to builtins.sort --- src/libexpr/primops.cc | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index 75d7465dd..ba568e38d 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -3725,6 +3725,32 @@ static RegisterPrimOp primop_sort({ This is a stable sort: it preserves the relative order of elements deemed equal by the comparator. + + *comparator* must impose a strict weak ordering on the set of values + in the *list*. This means that for any elements *a*, *b* and *c* from the + *list*, *comparator* must satisfy the following relations: + + 1. Transitivity + + ```nix + comparator a b && comparator b c -> comparator a c + ``` + + 1. Irreflexivity + + ```nix + comparator a a == false + ``` + + 1. Transitivity of equivalence + + ```nix + let equiv = a: b: (!comparator a b && !comparator b a); in + equiv a b && equiv b c -> equiv a c + ``` + + If the *comparator* violates any of these properties, then `builtins.sort` + reorders elements in an unspecified manner. )", .fun = prim_sort, });