打破OCaml中的循环 [英] Break a loop in OCaml
问题描述
我经常需要中断OCaml中的循环,至少有两种方法:
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 ...
我最关心的是运行时间的优化,只要程序易于阅读和理解即可.当存在多个嵌套循环时,while
使循环变得复杂的方式.
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.
我看到Internet的某个地方指出,在OCaml中引发和捕获异常非常昂贵.谁能证实我的说法是真的?
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?
所以我们有时应该使用while
方法,有时应该使用exception
方法?
So we should sometimes use the way by while
way, and sometimes use exception
way?
推荐答案
与其他语言相比,ocaml中的异常非常快(只要使用原始编译器即可.js_of_ocaml,ocaml-java等的情况有所不同. )
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.)
但是,带有编译while循环的解决方案仍然会更快一些.如果在例外情况下更易于阅读代码(至少在大多数情况下),我不会在乎最小的速度差异.
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.
这篇关于打破OCaml中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!