summary refs log tree commit diff
diff options
context:
space:
mode:
authorSilvan Mosberger <silvan.mosberger@tweag.io>2023-07-14 18:18:48 +0200
committerSilvan Mosberger <silvan.mosberger@tweag.io>2023-07-14 19:36:45 +0200
commitbc8fbc25723b05e0f909faa6589641867200775b (patch)
tree5f19cfd37b053399fc51ceb1f045cec496d5bf4b
parenta4f7840e1813bc389995083fac2b3bcd0ca6823d (diff)
downloadnixpkgs-bc8fbc25723b05e0f909faa6589641867200775b.tar
nixpkgs-bc8fbc25723b05e0f909faa6589641867200775b.tar.gz
nixpkgs-bc8fbc25723b05e0f909faa6589641867200775b.tar.bz2
nixpkgs-bc8fbc25723b05e0f909faa6589641867200775b.tar.lz
nixpkgs-bc8fbc25723b05e0f909faa6589641867200775b.tar.xz
nixpkgs-bc8fbc25723b05e0f909faa6589641867200775b.tar.zst
nixpkgs-bc8fbc25723b05e0f909faa6589641867200775b.zip
lib.lists.hasPrefix: init
-rw-r--r--lib/lists.nix15
-rw-r--r--lib/tests/misc.nix21
2 files changed, 36 insertions, 0 deletions
diff --git a/lib/lists.nix b/lib/lists.nix
index 5d9af0cf711..e12bc9048ef 100644
--- a/lib/lists.nix
+++ b/lib/lists.nix
@@ -612,6 +612,21 @@ rec {
     # Input list
     list: sublist count (length list) list;
 
+  /* Whether the first list is a prefix of the second list.
+
+  Type: hasPrefix :: [a] -> [a] -> bool
+
+  Example:
+    hasPrefix [ 1 2 ] [ 1 2 3 4 ]
+    => true
+    hasPrefix [ 0 1 ] [ 1 2 3 4 ]
+    => false
+  */
+  hasPrefix =
+    list1:
+    list2:
+    take (length list1) list2 == list1;
+
   /* Return a list consisting of at most `count` elements of `list`,
      starting at index `start`.
 
diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix
index ce980436c1b..5c824a066e1 100644
--- a/lib/tests/misc.nix
+++ b/lib/tests/misc.nix
@@ -480,6 +480,27 @@ runTests {
     ([ 1 2 3 ] == (take 4 [  1 2 3 ]))
   ];
 
+  testListHasPrefixExample1 = {
+    expr = lists.hasPrefix [ 1 2 ] [ 1 2 3 4 ];
+    expected = true;
+  };
+  testListHasPrefixExample2 = {
+    expr = lists.hasPrefix [ 0 1 ] [ 1 2 3 4 ];
+    expected = false;
+  };
+  testListHasPrefixLazy = {
+    expr = lists.hasPrefix [ 1 ] [ 1 (abort "lib.lists.hasPrefix is not lazy") ];
+    expected = true;
+  };
+  testListHasPrefixEmptyPrefix = {
+    expr = lists.hasPrefix [ ] [ 1 2 ];
+    expected = true;
+  };
+  testListHasPrefixEmptyList = {
+    expr = lists.hasPrefix [ 1 2 ] [ ];
+    expected = false;
+  };
+
   testFoldAttrs = {
     expr = foldAttrs (n: a: [n] ++ a) [] [
     { a = 2; b = 7; }