Skip to content

Commit 122e46b

Browse files
Make the helper a bit simpler to read and close handles properly
1 parent 45e2468 commit 122e46b

File tree

1 file changed

+32
-28
lines changed

1 file changed

+32
-28
lines changed
Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,42 @@
11
(* small helper to determine whether two files differ *)
22

3+
type comparison = Same | Different
4+
5+
let rec compare first second =
6+
match input_line first with
7+
| first_line -> (
8+
match input_line second with
9+
| second_line ->
10+
match String.equal first_line second_line with
11+
| true -> compare first second
12+
| false ->
13+
(* we found a difference between the lines *)
14+
Different
15+
| exception End_of_file ->
16+
(* the second file ended before the first *)
17+
Different)
18+
| exception End_of_file ->
19+
(* the first file ended first *)
20+
match input_line second with
21+
| _ ->
22+
(* the second file continues: a difference *)
23+
Different
24+
| exception End_of_file ->
25+
(* the second file ended too *)
26+
Same
27+
328
let main () =
429
let first = Sys.argv.(1) |> open_in in
530
let second = Sys.argv.(2) |> open_in in
6-
let rec loop () =
7-
match input_line first with
8-
| first_line -> (
9-
match input_line second with
10-
| second_line ->
11-
match String.equal first_line second_line with
12-
| true -> loop ()
13-
| false ->
14-
(* we found a difference between the lines *)
15-
exit 0
16-
| exception End_of_file ->
17-
(* the second file ended before the first *)
18-
exit 0
19-
)
20-
| exception End_of_file ->
21-
(* the first file ended first *)
22-
match input_line second with
23-
| _ ->
24-
(* the second file continues: a difference *)
25-
exit 1
26-
| exception End_of_file ->
27-
(* the second file ended too *)
28-
()
29-
in
30-
loop ();
31+
let comparison = compare first second in
3132
close_in first;
3233
close_in second;
33-
(* we didn't find a difference, exit with a failure code *)
34-
prerr_endline "The files appear to be identical";
35-
exit 1
34+
match comparison with
35+
| Same ->
36+
prerr_endline "The files appear to be identical";
37+
(* we didn't find a difference, exit with a failure code *)
38+
exit 1
39+
| Different -> ()
3640

3741
let () =
3842
main ()

0 commit comments

Comments
 (0)