summaryrefslogtreecommitdiffstats
path: root/lib/trivial.nix
diff options
context:
space:
mode:
authorJan Malakhovski <oxij@oxij.org>2017-12-07 21:26:30 +0000
committerJan Malakhovski <oxij@oxij.org>2018-02-09 19:51:05 +0000
commitee3220440da59e39154b520353a3d03a1abf3405 (patch)
treeaa3bf8018184d395869ffd2a32dd97632c2b100f /lib/trivial.nix
parent2341c81427420be95cd9f8640e3e96e3e317c645 (diff)
lib: implement `compare`, `splitByAndCompare`, and `compareLists`
Diffstat (limited to 'lib/trivial.nix')
-rw-r--r--lib/trivial.nix36
1 files changed, 36 insertions, 0 deletions
diff --git a/lib/trivial.nix b/lib/trivial.nix
index d8d51298143e..a928e1dbca98 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);