about summary refs log tree commit diff
path: root/lib/lists.nix
diff options
context:
space:
mode:
authorSilvan Mosberger <contact@infinisil.com>2023-08-14 21:15:54 +0200
committerGitHub <noreply@github.com>2023-08-14 21:15:54 +0200
commit87c5a6a84fcb94fd52507c24bb31c3b844775190 (patch)
tree847a78a99a35e132a81fb6706fa338c23934261f /lib/lists.nix
parent50d11650a71acbead4f84e75b5900680a1edd3f2 (diff)
parent9fdc0bb2bfa2d1dd631bb39f3b9e7cfec16bcd54 (diff)
Merge pull request #243511 from tweag/lib.lists.hasPrefix
`lib.lists.{hasPrefix,removePrefix}`: init
Diffstat (limited to 'lib/lists.nix')
-rw-r--r--lib/lists.nix34
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/lists.nix b/lib/lists.nix
index 3e058b3f1aef1..0800aeb654516 100644
--- a/lib/lists.nix
+++ b/lib/lists.nix
@@ -638,6 +638,40 @@ 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;
+
+  /* Remove the first list as a prefix from the second list.
+  Error if the first list isn't a prefix of the second list.
+
+  Type: removePrefix :: [a] -> [a] -> [a]
+
+  Example:
+    removePrefix [ 1 2 ] [ 1 2 3 4 ]
+    => [ 3 4 ]
+    removePrefix [ 0 1 ] [ 1 2 3 4 ]
+    => <error>
+  */
+  removePrefix =
+    list1:
+    list2:
+    if hasPrefix list1 list2 then
+      drop (length list1) list2
+    else
+      throw "lib.lists.removePrefix: First argument is not a list prefix of the second argument";
+
   /* Return a list consisting of at most `count` elements of `list`,
      starting at index `start`.