Break a loop in OCaml

末鹿安然 提交于 2019-12-30 11:28:09

问题


I often need to break a loop in OCaml, there are at least two ways:

(* by exception *)
try
  for i = 0 to 100 do
    ...
    if cond then raise BreakLoop
  done;
...
with BreakLoop -> ...

(* by while *)
let cond = ref false in
let i = ref 0 in
while (not !cond) && (i<= 100) do
  ...
  i := !i + 1
done;
if !cond then ...

What I care most is the optimisation of running time, as long as the program can be easily read and understood. The way while makes loops complicated when there are several nested loops.

I see somewhere in the Internet people state that throwing and catching an exception in OCaml is costly. Could anyone confirm me if it is true?

So we should sometimes use the way by while way, and sometimes use exception way?


回答1:


Compared to other languages, exceptions are very fast in ocaml (as long as you use the original compilers. Things are different for js_of_ocaml, ocaml-java, etc.)

However, the solution with compilicated while-loops will still be a little bit faster. I wouldn't care about the mininmal speed differences, if the code is easier to read with exceptions - at least in most cases.



来源:https://stackoverflow.com/questions/16937598/break-a-loop-in-ocaml

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