`lib.dropEnd` (#370558)

authored by Silvan Mosberger and committed by GitHub 0f880eb3 0b4b1319

+68 -2
+3 -2
lib/default.nix
··· 94 94 inherit (self.lists) singleton forEach map foldr fold foldl foldl' imap0 imap1 95 95 filter ifilter0 concatMap flatten remove findSingle findFirst any all count 96 96 optional optionals toList range replicate partition zipListsWith zipLists 97 - reverseList listDfs toposort sort sortOn naturalSort compareLists take 98 - drop sublist last init crossLists unique allUnique intersectLists 97 + reverseList listDfs toposort sort sortOn naturalSort compareLists 98 + take drop dropEnd sublist last init 99 + crossLists unique allUnique intersectLists 99 100 subtractLists mutuallyExclusive groupBy groupBy' concatLists genList 100 101 length head tail elem elemAt isList; 101 102 inherit (self.strings) concatStrings concatMapStrings concatImapStrings
+41
lib/lists.nix
··· 6 6 inherit (lib.strings) toInt; 7 7 inherit (lib.trivial) compare min id warn pipe; 8 8 inherit (lib.attrsets) mapAttrs; 9 + inherit (lib) max; 9 10 in 10 11 rec { 11 12 ··· 1496 1497 drop = 1497 1498 count: 1498 1499 list: sublist count (length list) list; 1500 + 1501 + /** 1502 + Remove the last (at most) N elements of a list. 1503 + 1504 + 1505 + # Inputs 1506 + 1507 + `count` 1508 + 1509 + : Number of elements to drop 1510 + 1511 + `list` 1512 + 1513 + : Input list 1514 + 1515 + # Type 1516 + 1517 + ``` 1518 + dropEnd :: Int -> [a] -> [a] 1519 + ``` 1520 + 1521 + # Examples 1522 + 1523 + :::{.example} 1524 + ## `lib.lists.dropEnd` usage example 1525 + 1526 + ```nix 1527 + dropEnd 2 [ "a" "b" "c" "d" ] 1528 + => [ "a" "b" ] 1529 + dropEnd 2 [ ] 1530 + => [ ] 1531 + ``` 1532 + ::: 1533 + 1534 + */ 1535 + dropEnd = 1536 + n: xs: 1537 + take 1538 + (max 0 (length xs - n)) 1539 + xs; 1499 1540 1500 1541 /** 1501 1542 Whether the first list is a prefix of the second list.
+24
lib/tests/misc.nix
··· 854 854 ([ 1 2 3 ] == (take 4 [ 1 2 3 ])) 855 855 ]; 856 856 857 + testDrop = let inherit (lib) drop; in testAllTrue [ 858 + # list index -1 is out of bounds 859 + # ([ 1 2 3 ] == (drop (-1) [ 1 2 3 ])) 860 + (drop 0 [ 1 2 3 ] == [ 1 2 3 ]) 861 + (drop 1 [ 1 2 3 ] == [ 2 3 ]) 862 + (drop 2 [ 1 2 3 ] == [ 3 ]) 863 + (drop 3 [ 1 2 3 ] == [ ]) 864 + (drop 4 [ 1 2 3 ] == [ ]) 865 + (drop 0 [ ] == [ ]) 866 + (drop 1 [ ] == [ ]) 867 + ]; 868 + 869 + testDropEnd = let inherit (lib) dropEnd; in testAllTrue [ 870 + (dropEnd 0 [ 1 2 3 ] == [ 1 2 3 ]) 871 + (dropEnd 1 [ 1 2 3 ] == [ 1 2 ]) 872 + (dropEnd 2 [ 1 2 3 ] == [ 1 ]) 873 + (dropEnd 3 [ 1 2 3 ] == [ ]) 874 + (dropEnd 4 [ 1 2 3 ] == [ ]) 875 + (dropEnd 0 [ ] == [ ]) 876 + (dropEnd 1 [ ] == [ ]) 877 + (dropEnd (-1) [ 1 2 3 ] == [ 1 2 3 ]) 878 + (dropEnd (-1) [ ] == [ ]) 879 + ]; 880 + 857 881 testListHasPrefixExample1 = { 858 882 expr = lists.hasPrefix [ 1 2 ] [ 1 2 3 4 ]; 859 883 expected = true;