diff --git a/lib/default.nix b/lib/default.nix index 68e5b8dea1eb..9fa3f4175a2a 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -87,7 +87,7 @@ let updateManyAttrsByPath; inherit (self.lists) singleton forEach foldr fold foldl foldl' imap0 imap1 concatMap flatten remove findSingle findFirst any all count - optional optionals toList range partition zipListsWith zipLists + optional optionals toList range replicate partition zipListsWith zipLists reverseList listDfs toposort sort naturalSort compareLists take drop sublist last init crossLists unique intersectLists subtractLists mutuallyExclusive groupBy groupBy'; diff --git a/lib/lists.nix b/lib/lists.nix index 602b13cf69cf..32b3f06b195f 100644 --- a/lib/lists.nix +++ b/lib/lists.nix @@ -303,6 +303,18 @@ rec { else genList (n: first + n) (last - first + 1); + /* Return a list with `n` copies of an element. + + Type: replicate :: int -> a -> [a] + + Example: + replicate 3 "a" + => [ "a" "a" "a" ] + replicate 2 true + => [ true true ] + */ + replicate = n: elem: genList (_: elem) n; + /* Splits the elements of a list in two lists, `right` and `wrong`, depending on the evaluation of a predicate. diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index c719fcf5d4fa..7e52a2e8f0ab 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -459,6 +459,11 @@ runTests { expected = [2 30 40 42]; }; + testReplicate = { + expr = replicate 3 "a"; + expected = ["a" "a" "a"]; + }; + testToIntShouldConvertStringToInt = { expr = toInt "27"; expected = 27;