I want to write a function that implements basic usage of grep: matching a pattern in a file. And I want to match_file_pattern to return a list of matched lines. But the code here cannot compile, the error is:
Error: This expression has type string list but an expression was expected of type unit
And the code is:
let match_file pattern file_name =
let matched_lines = ref [] in
let ic = open_in file_name in
try
while true
do
let line = input_line ic in
if (Str.string_match (Str.regexp pattern) line 0)
then
matched_lines := line::!matched_lines
done;**(*!matched_lines*)**(*I need add this to compile successfully*)
with End_of_file ->
close_in ic;
List.rev !matched_lines;;
I think the error is caused by in ocaml
, close_in ic; List.rev !matched_lines
is grouped into a subexpression of "with" keyword, so its type should match with "try" expression. I try to find ways to break the relation between close_in ic;
and List.rev !matched_lines
, but failed.