是否可以在函数内部定义异常

Is it possible to define an exception inside a function

在 OCaml 中实现 "early returns" 的一种方法是通过异常:

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 就足够了。