在 OCaml 中实现“提前返回”的一种方法是通过异常:
exception Exit
let myfunc () =
try
for i = 0 to .... do
if .. then raise Exit
done; false
with Exit -> true
但是,有没有办法声明这一点Exit
函数体中出现异常,因此其名称对模块中的其他函数不可见?
(* 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
是的,您想要的可以通过使用本地模块来实现:
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
如果您想对程序的其余大部分部分隐藏它,请在下一个模块界面上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)