Unverified Commit 87c5a6a8 authored by Silvan Mosberger's avatar Silvan Mosberger Committed by GitHub
Browse files

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

`lib.lists.{hasPrefix,removePrefix}`: init
parents 50d11650 9fdc0bb2
Loading
Loading
Loading
Loading
+34 −0
Original line number Diff line number Diff line
@@ -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`.

+38 −0
Original line number Diff line number Diff line
@@ -492,6 +492,44 @@ 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;
  };

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