OCaml split a list into fixed-size batches
OCaml
let chunk size items =
if size <= 0 then invalid_arg "chunk: size must be positive";
let rec split count acc rest =
if count = 0 then (List.rev acc, rest)
else match rest with
| [] -> (List.rev acc, [])
| x :: xs -> split (count - 1) (x :: acc) xs
in
let rec loop acc rest =
match rest with
| [] -> List.rev acc
| _ ->
let batch, remaining = split size [] rest in
loop (batch :: acc) remaining
in
loop [] items