From ee3220440da59e39154b520353a3d03a1abf3405 Mon Sep 17 00:00:00 2001 From: Jan Malakhovski Date: Thu, 7 Dec 2017 21:26:30 +0000 Subject: lib: implement `compare`, `splitByAndCompare`, and `compareLists` --- lib/trivial.nix | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'lib/trivial.nix') diff --git a/lib/trivial.nix b/lib/trivial.nix index d8d51298143..a928e1dbca9 100644 --- a/lib/trivial.nix +++ b/lib/trivial.nix @@ -81,6 +81,42 @@ rec { */ mod = base: int: base - (int * (builtins.div base int)); + /* C-style comparisons + + a < b, compare a b => -1 + a == b, compare a b => 0 + a > b, compare a b => 1 + */ + compare = a: b: + if a < b + then -1 + else if a > b + then 1 + else 0; + + /* Split type into two subtypes by predicate `p`, take all elements + of the first subtype to be less than all the elements of the + second subtype, compare elements of a single subtype with `yes` + and `no` respectively. + + Example: + + let cmp = splitByAndCompare (hasPrefix "foo") compare compare; in + + cmp "a" "z" => -1 + cmp "fooa" "fooz" => -1 + + cmp "f" "a" => 1 + cmp "fooa" "a" => -1 + # while + compare "fooa" "a" => 1 + + */ + splitByAndCompare = p: yes: no: a: b: + if p a + then if p b then yes a b else -1 + else if p b then 1 else no a b; + /* Reads a JSON file. */ importJSON = path: builtins.fromJSON (builtins.readFile path); -- cgit 1.4.1