summary refs log tree commit diff
path: root/lib
diff options
context:
space:
mode:
authorSilvan Mosberger <contact@infinisil.com>2023-02-07 06:16:09 +0100
committerGitHub <noreply@github.com>2023-02-07 06:16:09 +0100
commit0a60663e67fd32a27301aecad3a3bbca76932c39 (patch)
treea259a826abd7725ccb9097183e6202703d912225 /lib
parent4ee1a6c3ae9ebf58183e446aa53e5efaac34cbb3 (diff)
parent7c4abbf80e1471d7844aae825f6d1015ce315a48 (diff)
downloadnixpkgs-0a60663e67fd32a27301aecad3a3bbca76932c39.tar
nixpkgs-0a60663e67fd32a27301aecad3a3bbca76932c39.tar.gz
nixpkgs-0a60663e67fd32a27301aecad3a3bbca76932c39.tar.bz2
nixpkgs-0a60663e67fd32a27301aecad3a3bbca76932c39.tar.lz
nixpkgs-0a60663e67fd32a27301aecad3a3bbca76932c39.tar.xz
nixpkgs-0a60663e67fd32a27301aecad3a3bbca76932c39.tar.zst
nixpkgs-0a60663e67fd32a27301aecad3a3bbca76932c39.zip
Merge pull request #206611 from h7x4/lib-lists-add-repeat
lib.lists: add `replicate`
Diffstat (limited to 'lib')
-rw-r--r--lib/default.nix2
-rw-r--r--lib/lists.nix12
-rw-r--r--lib/tests/misc.nix5
3 files changed, 18 insertions, 1 deletions
diff --git a/lib/default.nix b/lib/default.nix
index b1441c72810..dc4df957541 100644
--- a/lib/default.nix
+++ b/lib/default.nix
@@ -88,7 +88,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 9f69485b408..2186cd4a79f 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 c14bddb11a1..406656dac1a 100644
--- a/lib/tests/misc.nix
+++ b/lib/tests/misc.nix
@@ -479,6 +479,11 @@ runTests {
     expected = [2 30 40 42];
   };
 
+  testReplicate = {
+    expr = replicate 3 "a";
+    expected = ["a" "a" "a"];
+  };
+
   testToIntShouldConvertStringToInt = {
     expr = toInt "27";
     expected = 27;