Is it possible to define an exception inside a function

柔情痞子 提交于 2020-01-13 04:59:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!