diff options
author | Jan Malakhovski <oxij@oxij.org> | 2017-12-07 21:26:30 +0000 |
---|---|---|
committer | Jan Malakhovski <oxij@oxij.org> | 2018-02-09 19:51:05 +0000 |
commit | ee3220440da59e39154b520353a3d03a1abf3405 (patch) | |
tree | aa3bf8018184d395869ffd2a32dd97632c2b100f /lib/trivial.nix | |
parent | 2341c81427420be95cd9f8640e3e96e3e317c645 (diff) | |
download | nixlib-ee3220440da59e39154b520353a3d03a1abf3405.tar nixlib-ee3220440da59e39154b520353a3d03a1abf3405.tar.gz nixlib-ee3220440da59e39154b520353a3d03a1abf3405.tar.bz2 nixlib-ee3220440da59e39154b520353a3d03a1abf3405.tar.lz nixlib-ee3220440da59e39154b520353a3d03a1abf3405.tar.xz nixlib-ee3220440da59e39154b520353a3d03a1abf3405.tar.zst nixlib-ee3220440da59e39154b520353a3d03a1abf3405.zip |
lib: implement `compare`, `splitByAndCompare`, and `compareLists`
Diffstat (limited to 'lib/trivial.nix')
-rw-r--r-- | lib/trivial.nix | 36 |
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); |