ron*_*ron 3 ocaml exception pattern-matching matching
作为Ocaml的初学者,我有这个当前的工作代码:
...
let ch_in = open_in input_file in
try
proc_lines ch_in
with End_of_file -> close_in ch_in;;
Run Code Online (Sandbox Code Playgroud)
现在我想为不存在的输入文件添加错误处理,我写道:
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 -> () ;;
Run Code Online (Sandbox Code Playgroud)
并获取一条错误消息:此模式匹配类型'a option的值,但此处用于匹配最后一行的exn类型的值.如果我代替无为_,我得到不完全匹配的错误.
我读到exn是异常类型.我确定我不明白这里到底发生了什么,所以请指出正确的方向.谢谢!
当嵌入模式匹配到其他模式匹配中时,您需要使用( ... )或者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 -> () ;;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2165 次 |
| 最近记录: |