diff options
author | h7x4 <h7x4@nani.wtf> | 2022-12-17 21:57:17 +0100 |
---|---|---|
committer | h7x4 <h7x4@nani.wtf> | 2023-02-06 20:40:47 +0100 |
commit | 7c4abbf80e1471d7844aae825f6d1015ce315a48 (patch) | |
tree | 4732d1dfe37370875eed0d8317d02b7b4237948e | |
parent | 41169b15c53350d893d3715cf19eed598d3dbec1 (diff) | |
download | nixpkgs-7c4abbf80e1471d7844aae825f6d1015ce315a48.tar nixpkgs-7c4abbf80e1471d7844aae825f6d1015ce315a48.tar.gz nixpkgs-7c4abbf80e1471d7844aae825f6d1015ce315a48.tar.bz2 nixpkgs-7c4abbf80e1471d7844aae825f6d1015ce315a48.tar.lz nixpkgs-7c4abbf80e1471d7844aae825f6d1015ce315a48.tar.xz nixpkgs-7c4abbf80e1471d7844aae825f6d1015ce315a48.tar.zst nixpkgs-7c4abbf80e1471d7844aae825f6d1015ce315a48.zip |
lib.lists: add `replicate`
`replicate` returns n copies of an element as a list. Co-Authored-By: Silvan Mosberger <contact@infinisil.com>
-rw-r--r-- | lib/default.nix | 2 | ||||
-rw-r--r-- | lib/lists.nix | 12 | ||||
-rw-r--r-- | lib/tests/misc.nix | 5 |
3 files changed, 18 insertions, 1 deletions
diff --git a/lib/default.nix b/lib/default.nix index 68e5b8dea1e..9fa3f4175a2 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 602b13cf69c..32b3f06b195 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 c719fcf5d4f..7e52a2e8f0a 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; |