From 66261e9961254a5c8a7c096e091fd42deb988cee Mon Sep 17 00:00:00 2001 From: Felix Buehler Date: Sun, 25 Jun 2023 13:16:06 +0200 Subject: [PATCH] lib.lists.allUnique: init --- lib/default.nix | 2 +- lib/lists.nix | 13 +++++++++++++ lib/tests/misc.nix | 9 +++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/default.nix b/lib/default.nix index fe737a125e680..80fc17985879a 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -92,7 +92,7 @@ let concatMap flatten remove findSingle findFirst any all count optional optionals toList range replicate partition zipListsWith zipLists reverseList listDfs toposort sort naturalSort compareLists take - drop sublist last init crossLists unique intersectLists + drop sublist last init crossLists unique allUnique intersectLists subtractLists mutuallyExclusive groupBy groupBy'; inherit (self.strings) concatStrings concatMapStrings concatImapStrings intersperse concatStringsSep concatMapStringsSep diff --git a/lib/lists.nix b/lib/lists.nix index 3835e3ba69cb8..15047f488f4da 100644 --- a/lib/lists.nix +++ b/lib/lists.nix @@ -821,6 +821,19 @@ rec { */ unique = foldl' (acc: e: if elem e acc then acc else acc ++ [ e ]) []; + /* Check if list contains only unique elements. O(n^2) complexity. + + Type: allUnique :: [a] -> bool + + Example: + allUnique [ 3 2 3 4 ] + => false + allUnique [ 3 2 4 1 ] + => true + */ + allUnique = list: (length (unique list) == length list); + + /* Intersects list 'e' and another list. O(nm) complexity. Example: diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index 0d30e93aafb9d..06cb5e763e2c2 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -726,6 +726,15 @@ runTests { expected = 7; }; + testAllUnique_true = { + expr = allUnique [ 3 2 4 1 ]; + expected = true; + }; + testAllUnique_false = { + expr = allUnique [ 3 2 3 4 ]; + expected = false; + }; + # ATTRSETS testConcatMapAttrs = {