我不明白 try ... with ... Ocaml 功能的行为。
这里有一个小样本来重现我的问题:
let () =
try int_of_string "4" with
| Failure -> -1
| n -> n
我用
编译ocamlc 测试.ml
然后我收到此错误:
文件“test.ml”,第 2 行,字符 6-23:
2 | 尝试 int_of_string "4" 与错误:此表达式的类型为 int,但表达式应为 unit 类型
如何修改我的小代码示例以使其正常工作?
您的代码可以解读为
let () = (* I expect an unit result *)
try int_of_string "4"
(* if the call to `int_of_string` succeeds returns this result,
which is an int *)
with (* otherwise if an exception was raised* *)
| Failure ->
(* returns 1 if the raised exception was the `Failure` exception *)
-1
| n -> n (* otherwise returns the exception `n` *)
由于有很多小剪纸而失败。修正后的版本是
let n =
try int_of_string "4" with
| Failure _ (* Failure contains a error message as an argument *) -> - 1
尽管如此,我建议使用
match ... with exception ... -> ...
结构,它可能更接近你的直觉
let n = match int_of_string "4" with
| exception Failure _msg -> -1
| x -> x (* if there was no exception, returns the result *)
但你也可以通过
避免异常let n = match int_of_string_opt "4" with
| None -> -1
| Some x -> x
甚至
let n = Option.value ~default:(-1) (int_of_string_opt "4")