Exception 使用异常在文件行上中断迭代

Exception 使用异常在文件行上中断迭代,exception,ocaml,Exception,Ocaml,有些文本文件需要逐行操作。我编写了一个with file函数,如下所示: 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);; 因此,我可以将每个文件操作为: withFile "file1.txt

有些文本文件需要逐行操作。我编写了一个
with file
函数,如下所示:

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);;
因此,我可以将每个文件操作为:

withFile "file1.txt" (fun line -> (*...*))
withFile "file2.txt" (fun line -> (*...*))
...
但我不知道如何优雅地退出时,我不想处理所有的行。例如:

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

任何建议都将不胜感激

您的函数
iter\u行
不是尾部递归的,这意味着如果以这种方式处理非常大的文件,可能会耗尽堆栈空间。它不是尾部递归的原因是它必须建立并删除
try。。。具有捕获异常的
机制

除此之外,这对我来说真的很好。这种高阶函数就是OCaml(和FP)的全部内容

使其尾部递归的一种方法是将异常处理移出包含函数。我还将更具体地介绍您要处理的异常。所以你得到这个:

let withFile fn handle =
    let rec iter_lines fh =
        handle (input_line fh);
        iter_lines fh
    in
    let fh = open_in fn in
    try iter_lines fh
    with End_of_file -> close_in fh
如果希望能够提前退出,一种简单的方法是让handle函数返回一个布尔值,告诉您是否继续处理行。你会得到这样的结果:

let withFile fn handle =
    let rec iter_lines fh =
        if handle (input_line fh) then
            iter_lines fh
    in
    let fh = open_in fn in
    try iter_lines fh
    with End_of_file -> close_in fh
let withFile fn handle =
    let rec iter_lines fh =
        handle (input_line fh);
        iter_lines fh
    in
    let fh = open_in fn in
    try iter_lines fh
    with e ->
        (close_in fh; if e <> End_of_file then raise e)
如果希望能够使用异常提前退出,则需要捕获
with file
中的所有异常,关闭该文件,然后重新引发除
结束\u文件
之外的任何异常。这将为您提供如下代码:

let withFile fn handle =
    let rec iter_lines fh =
        if handle (input_line fh) then
            iter_lines fh
    in
    let fh = open_in fn in
    try iter_lines fh
    with End_of_file -> close_in fh
let withFile fn handle =
    let rec iter_lines fh =
        handle (input_line fh);
        iter_lines fh
    in
    let fh = open_in fn in
    try iter_lines fh
    with e ->
        (close_in fh; if e <> End_of_file then raise e)
let with file fn handle=
让我们记录下iter_线fh=
手柄(输入线fh);
iter_线fh
在里面
设fh=在fn中打开
试试iter_线fh
使用e->
(在fh中关闭\ U;如果\ U文件的e结束\ U,则引发e)