【问题标题】:Ocaml exception handling for opening input channel打开输入通道的 Ocaml 异常处理
【发布时间】:2010-03-07 13:50:40
【问题描述】:

作为 Ocaml 的初学者,我有这个当前的工作代码:

...
let ch_in = open_in input_file in
try
    proc_lines ch_in
with End_of_file -> close_in ch_in;;

现在我想为不存在的输入文件添加错误处理,我写了这个:

let ch_in = try Some (open_in input_file) with _ -> None in
match ch_in with
| Some x -> try proc_lines x with End_of_file -> close_in x
| None -> () ;;

并得到一条错误消息:此模式匹配 'a 选项类型的值 但是在这里用于匹配最后一行的 exn 类型的值。如果我用 None 代替 _,我会收到关于不完全匹配的错误。

我读到 exn 是异常类型。我确定我不明白这里到底发生了什么,所以请指出正确的方向。谢谢!

【问题讨论】:

    标签: exception pattern-matching ocaml matching


    【解决方案1】:

    当在其他模式匹配中嵌入模式匹配时,您需要使用( ... )begin ... end(括号的语法糖)来封装嵌入的匹配:

    let ch_in = try Some (open_in input_file) with _ -> None in
    match ch_in with
    | Some x -> (try proc_lines x with End_of_file -> close_in x)
    | None -> () ;;
    

    【讨论】:

    • 谢谢,现在我看到解析器认为“| None -> ()”属于“try”的匹配项
    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2013-05-24
    • 1970-01-01
    相关资源
    最近更新 更多