From ae886c2f0890b40110472d43fb10ef377dee8018 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Sun, 24 Jan 2021 11:18:53 -0500 Subject: [PATCH] add `CCList.chunks` --- src/core/CCList.ml | 11 +++++++++++ src/core/CCList.mli | 7 +++++++ src/core/CCListLabels.mli | 7 +++++++ 3 files changed, 25 insertions(+) diff --git a/src/core/CCList.ml b/src/core/CCList.ml index 21f2569f..0aef95d4 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -922,6 +922,17 @@ let sublists_of_len ?(last=fun _ -> None) ?offset n l = [[1;2]; [3;4]] (subs 2 [1;2;3;4;5]) *) +let chunks n l = sublists_of_len ~last:(fun x -> Some x) n l + +(*$Q + Q.(small_list small_int) (fun l -> \ + l = (chunks 3 l |> List.flatten)) + Q.(small_list small_int) (fun l -> \ + l = (chunks 5 l |> List.flatten)) + Q.(small_list small_int) (fun l -> \ + List.for_all (fun u -> List.length u <= 5) (chunks 5 l)) +*) + let intersperse x l = let rec aux_direct i x l = match l with | [] -> [] diff --git a/src/core/CCList.mli b/src/core/CCList.mli index 54c6cda0..ae933c88 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -323,6 +323,13 @@ val sublists_of_len : @since 1.0, but only @since 1.5 with labels *) +val chunks : int -> 'a list -> 'a list list +(** [chunks n l] returns consecutives chunks of size at most [n] from [l]. + Each item of [l] will occur in exactly one chunk. Only the last chunk + might be of length smaller than [n]. + Invariant: [(chunks n l |> List.flatten) = l]. + @since NEXT_RELEASE *) + val intersperse : 'a -> 'a list -> 'a list (** [intersperse x l] inserts the element [x] between adjacent elements of the list [l]. @since 2.1, but only diff --git a/src/core/CCListLabels.mli b/src/core/CCListLabels.mli index 1fa40a1d..8b5b87ca 100644 --- a/src/core/CCListLabels.mli +++ b/src/core/CCListLabels.mli @@ -327,6 +327,13 @@ val sublists_of_len : @since 1.0, but only @since 1.5 with labels *) +val chunks : int -> 'a list -> 'a list list +(** [chunks n l] returns consecutives chunks of size at most [n] from [l]. + Each item of [l] will occur in exactly one chunk. Only the last chunk + might be of length smaller than [n]. + Invariant: [(chunks n l |> List.flatten) = l]. + @since NEXT_RELEASE *) + val intersperse : x:'a -> 'a list -> 'a list (** [intersperse ~x l] inserts the element [x] between adjacent elements of the list [l]. @since 2.1, but only