let line_count filename = let f = open_in filename in let rec loop count = match (readline f) with | Some(_) -> loop (count+1) | None -> count in loop 0;;Something like this should be even faster: exception Done of int let line_count file = let rec loop count = let _ = try input_line f with End_of_file -> raise (Done count) in loop (count + 1) in try loop 0 with Done x -> x as it avoids unnecessary consing in the inner loop. __