问题
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