lib.lists.removePrefix: init

This commit is contained in:
Silvan Mosberger 2023-07-14 18:28:38 +02:00
parent bc8fbc2572
commit 9fdc0bb2bf
2 changed files with 36 additions and 0 deletions

View File

@ -627,6 +627,25 @@ rec {
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`.

View File

@ -501,6 +501,23 @@ runTests {
expected = false;
};
testListRemovePrefixExample1 = {
expr = lists.removePrefix [ 1 2 ] [ 1 2 3 4 ];
expected = [ 3 4 ];
};
testListRemovePrefixExample2 = {
expr = (builtins.tryEval (lists.removePrefix [ 0 1 ] [ 1 2 3 4 ])).success;
expected = false;
};
testListRemovePrefixEmptyPrefix = {
expr = lists.removePrefix [ ] [ 1 2 ];
expected = [ 1 2 ];
};
testListRemovePrefixEmptyList = {
expr = (builtins.tryEval (lists.removePrefix [ 1 2 ] [ ])).success;
expected = false;
};
testFoldAttrs = {
expr = foldAttrs (n: a: [n] ++ a) [] [
{ a = 2; b = 7; }