Merge pull request #243511 from tweag/lib.lists.hasPrefix

`lib.lists.{hasPrefix,removePrefix}`: init

authored by

Silvan Mosberger and committed by
GitHub
87c5a6a8 50d11650

+72
+34
lib/lists.nix
··· 638 # Input list 639 list: sublist count (length list) list; 640 641 /* Return a list consisting of at most `count` elements of `list`, 642 starting at index `start`. 643
··· 638 # Input list 639 list: sublist count (length list) list; 640 641 + /* Whether the first list is a prefix of the second list. 642 + 643 + Type: hasPrefix :: [a] -> [a] -> bool 644 + 645 + Example: 646 + hasPrefix [ 1 2 ] [ 1 2 3 4 ] 647 + => true 648 + hasPrefix [ 0 1 ] [ 1 2 3 4 ] 649 + => false 650 + */ 651 + hasPrefix = 652 + list1: 653 + list2: 654 + take (length list1) list2 == list1; 655 + 656 + /* Remove the first list as a prefix from the second list. 657 + Error if the first list isn't a prefix of the second list. 658 + 659 + Type: removePrefix :: [a] -> [a] -> [a] 660 + 661 + Example: 662 + removePrefix [ 1 2 ] [ 1 2 3 4 ] 663 + => [ 3 4 ] 664 + removePrefix [ 0 1 ] [ 1 2 3 4 ] 665 + => <error> 666 + */ 667 + removePrefix = 668 + list1: 669 + list2: 670 + if hasPrefix list1 list2 then 671 + drop (length list1) list2 672 + else 673 + throw "lib.lists.removePrefix: First argument is not a list prefix of the second argument"; 674 + 675 /* Return a list consisting of at most `count` elements of `list`, 676 starting at index `start`. 677
+38
lib/tests/misc.nix
··· 492 ([ 1 2 3 ] == (take 4 [ 1 2 3 ])) 493 ]; 494 495 testFoldAttrs = { 496 expr = foldAttrs (n: a: [n] ++ a) [] [ 497 { a = 2; b = 7; }
··· 492 ([ 1 2 3 ] == (take 4 [ 1 2 3 ])) 493 ]; 494 495 + testListHasPrefixExample1 = { 496 + expr = lists.hasPrefix [ 1 2 ] [ 1 2 3 4 ]; 497 + expected = true; 498 + }; 499 + testListHasPrefixExample2 = { 500 + expr = lists.hasPrefix [ 0 1 ] [ 1 2 3 4 ]; 501 + expected = false; 502 + }; 503 + testListHasPrefixLazy = { 504 + expr = lists.hasPrefix [ 1 ] [ 1 (abort "lib.lists.hasPrefix is not lazy") ]; 505 + expected = true; 506 + }; 507 + testListHasPrefixEmptyPrefix = { 508 + expr = lists.hasPrefix [ ] [ 1 2 ]; 509 + expected = true; 510 + }; 511 + testListHasPrefixEmptyList = { 512 + expr = lists.hasPrefix [ 1 2 ] [ ]; 513 + expected = false; 514 + }; 515 + 516 + testListRemovePrefixExample1 = { 517 + expr = lists.removePrefix [ 1 2 ] [ 1 2 3 4 ]; 518 + expected = [ 3 4 ]; 519 + }; 520 + testListRemovePrefixExample2 = { 521 + expr = (builtins.tryEval (lists.removePrefix [ 0 1 ] [ 1 2 3 4 ])).success; 522 + expected = false; 523 + }; 524 + testListRemovePrefixEmptyPrefix = { 525 + expr = lists.removePrefix [ ] [ 1 2 ]; 526 + expected = [ 1 2 ]; 527 + }; 528 + testListRemovePrefixEmptyList = { 529 + expr = (builtins.tryEval (lists.removePrefix [ 1 2 ] [ ])).success; 530 + expected = false; 531 + }; 532 + 533 testFoldAttrs = { 534 expr = foldAttrs (n: a: [n] ++ a) [] [ 535 { a = 2; b = 7; }