问题
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
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
回答1:
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
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.
来源:https://stackoverflow.com/questions/33312718/is-it-possible-to-define-an-exception-inside-a-function