fix(map_by_2): Fixed bug in implementation and added some unit tests

This commit is contained in:
Master Builder 2023-08-04 19:13:32 +00:00 committed by Simon Cruanes
parent e72026b616
commit 6fdbc2c88f
2 changed files with 19 additions and 1 deletions

View file

@ -114,7 +114,7 @@ let map_by_2 f seq k =
let f y =
match !r with
| None -> r := Some y
| Some x -> k (f x y)
| Some x -> r := None; k (f x y)
in
seq f;
match !r with

View file

@ -347,3 +347,21 @@ let () =
let () =
let errcode = QCheck_base_runner.run_tests ~colors:false !qchecks in
if errcode <> 0 then exit errcode
(* map_by_2 tests *)
let test = OUnit.assert_equal ~printer:Q.Print.(list int)
let () = test [] (map_by_2 (fun a _ -> a) (of_list []) |> to_list)
(* Test empty iterator *)
let () = test [1] (map_by_2 (fun _ b -> b) (of_list [1]) |> to_list)
let () = test [3] (map_by_2 (fun _ b -> b) (1--3) |> drop 1 |> to_list)
let () = test [9] (map_by_2 (fun _ b -> b) (1--9) |> drop 4 |> to_list)
(* Odd number of elements should leave the last element in the iterator.
For an increasing integer range [1,2k] (fun _ b -> b) returns only
even numbers so this is sufficient to test that this element is left
in the iterator. *)
let () = test [1] (map_by_2 (fun a _ -> a) (1--2) |> to_list)
let () = test [2] (map_by_2 (fun _ b -> b) (1--2) |> to_list)
(* Test two elements *)
let () = test [1;3;5;7;9] (map_by_2 (fun a _ -> a) (1--10) |> to_list)
let () = test [2;4;6;8;10] (map_by_2 (fun _ b -> b) (1--10) |> to_list)
(* Test more than two elements *)