Whhether or not it is an elegant way in such a situation?

Posted by z_axis on Stack Overflow See other posts from Stack Overflow or by z_axis
Published on 2011-11-12T01:11:37Z Indexed on 2011/11/12 1:51 UTC
Read the original article Hit count: 162

Filed under:

There are some text files which needed to be manipulated line by line. I wrote a withFile function as below:

let withFile fn handle =
    let rec iter_lines fh =
    try
        handle (input_line fh);
        iter_lines fh
    with _ -> close_in fh in
    iter_lines (open_in fn);;

So i can manipulate each file as :

withFile "file1.txt" (fun line -> (*...*))
withFile "file2.txt" (fun line -> (*...*))
...

But i amnot sure how to exit elehantly when i donot want to handle all lines. For example:

withFile "file3.txt" (fun line ->
   (*when the line meets some condition, i will exit without handling other lines*)
);

Any suggestion is appreciated !

© Stack Overflow or respective owner

Related posts about ocaml