Skip to content

Commit

Permalink
Reimport Std.List for splitting list
Browse files Browse the repository at this point in the history
  • Loading branch information
xvw committed Nov 19, 2024
1 parent 9ac4bb6 commit 1372da5
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/std/list.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
let split_at n list =
if n < 1
then [], list
else (
let rec aux acc n = function
| [] -> Stdlib.List.rev acc, []
| x :: xs as rest ->
if n < 1 then Stdlib.List.rev acc, rest else aux (x :: acc) (pred n) xs
in
aux [] n list)
;;

let split_by_size size list =
let rec aux acc = function
| [] -> Stdlib.List.rev acc
| list ->
let x, xs = split_at size list in
aux (x :: acc) xs
in
aux [] list
;;
1 change: 1 addition & 0 deletions lib/std/list.mli
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
val split_by_size : int -> 'a list -> 'a list list
32 changes: 32 additions & 0 deletions test/std/list_test.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
let pp_list pp ppf list =
let pplist =
Format.pp_print_list ~pp_sep:(fun ppf () -> Format.fprintf ppf ";") pp
in
Format.fprintf ppf "[%a]" pplist list
;;

let dump list = Format.printf "%a" (pp_list (pp_list Format.pp_print_int)) list

let%expect_test "Splitting empty list" =
dump @@ Std.List.split_by_size 3 [];
[%expect {| [] |}]
;;

let%expect_test "Splitting list - 1" =
dump @@ Std.List.split_by_size 1 [ 1; 2; 3; 4; 5 ];
[%expect {| [[1];[2];[3];[4];[5]] |}]
;;

let%expect_test "Splitting list - 2" =
dump
@@ Std.List.split_by_size
3
[ 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15 ];
[%expect {| [[1;2;3];[4;5;6];[7;8;9];[10;11;12];[13;14;15]] |}]
;;

let%expect_test "Splitting list - 2" =
dump
@@ Std.List.split_by_size 4 [ 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 14; 15 ];
[%expect {| [[1;2;3;4];[5;6;7;8];[9;10;11;12];[14;15]] |}]
;;

0 comments on commit 1372da5

Please sign in to comment.