lib.lists.hasPrefix: init

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

View file

@ -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`.

View file

@ -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; }