是否可以在函数内定义异常 [英] Is it possible to define an exception inside a function
本文介绍了是否可以在函数内定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在OCaml中实现提前回报"的一种方法是通过异常:
One way to implement "early returns" in OCaml is via exceptions:
exception Exit
let myfunc () =
try
for i = 0 to .... do
if .. then raise Exit
done; false
with Exit -> true
但是,有没有一种方法可以在函数的主体中声明此Exit
异常,因此其名称对模块中的其他函数不可见?
However, is there a way to declare this Exit
exception in the body of the function, so its name is not visible to other functions in the module?
(* I would like to do this, but it gives a syntax error *)
let myfunc () =
exception Exit
try
for i = 0 to .... do
if .. then raise Exit
done; false
with Exit -> true
推荐答案
是的,可以通过使用本地模块来实现所需的操作:
Yes, what you want is possible by using a local module:
let myfunc () =
let module M = struct exception Exit end in
try
for i = 0 to 3 do
if true then raise M.Exit
done; false
with M.Exit -> true
但是,这种风格并不特别令人愉快,因此我不推荐使用.如果要在程序的大多数其余部分中隐藏Exit
,则只需在下一个模块界面上显示Exit
就足够了.
That style is not particularly pleasant to read, though, so I wouldn't recommend it. It is enough to omit showing Exit
at the next module interface if you want to hide it from most of the rest of the program.
这篇关于是否可以在函数内定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文