-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Reimport
Std.List
for splitting list
- Loading branch information
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
;; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
val split_by_size : int -> 'a list -> 'a list list |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]] |}] | ||
;; |