我经常需要打破OCaml中循环,至少有两种方式:打破循环OCaml中
(* 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
会使循环变得复杂。
我在互联网的某个地方看到人们说,在OCaml中抛出和捕捉异常代价很高。任何人都可以证实我是否属实?
那么我们有时候应该用while
的方式来使用,有时用exception
的方式呢?
您可能对[this]感兴趣(http://caml.inria.fr/mantis/view.php?id=5935)讨论。另外请注意,您可以使用异常[Exit](http://caml.inria.fr/pub/docs/manual-ocaml-4.00/libref/Pervasives.html#EXCEPTIONExit),而不是定义自己的。 –
考虑使用尾递归:'let rec loop i acc = if i> 100 || cond then acc else loop(i + 1)(f acc)'。但我并不是说“总是这样做”。 – lukstafi
借调。代码中有很多不必要的可变性。不要使用循环,只考虑条件满足时才进行递归调用。 –