gpt4 book ai didi

exception - 在 OCaml 中打破循环

转载 作者:行者123 更新时间:2023-12-02 05:01:50 26 4
gpt4 key购买 nike

我经常需要在 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 的方式会使循环变得复杂。

我在 Internet 的某个地方看到有人说在 OCaml 中抛出和捕获异常的成本很高。谁能证实我是不是真的?

那么我们应该有时使用while方式,有时使用exception方式?

最佳答案

与其他语言相比,ocaml 中的异常非常快(只要您使用原始编译器。js_of_ocaml、ocaml-java 等情况有所不同)

但是,使用复杂的 while 循环的解决方案仍然会快一点。我不会关心最小的速度差异,如果代码更容易阅读,但有异常(exception)——至少在大多数情况下是这样。

关于exception - 在 OCaml 中打破循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16937598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com