如何返回OCaml中for循环的索引? [英] How to return the index of a for loop in OCaml?
问题描述
let find_free_next heap start =
for i = start((Array.length heap)-1)do
match heap。(i)with
Hdr(Free(h),g) - >
i
完成
如何以整数形式返回循环的索引一旦匹配被发现?
如果你想坚持命令式的风格,你可以使用异常退出循环:
异常发现int
let find_free_next heap start =
尝试
for i = start到Array.length heap - 1 do
match heap。(i)with
| Hdr(Free(h),g) - >提高(找到我)
| _ - > ()(*如果它不是你正在寻找的*)
完成;
用
|提升Not_found
找到n - > n
但通常情况下,功能风格在OCaml中更受欢迎:
let find_free_next heap start =
let len = Array.length heap in
let rec find i =
if i> = len then None
else
match heap。(i)with
| Hdr(Free h,g) - >一些我
| _ - >在
中查找(i + 1)
查找开始
在这个例子中,两个版本没有太大的区别,但是必须谨慎使用退出循环/递归的异常。你可以很容易地引入控制流程错误,而且它们有时很难调试。
顺便说一句,你可以使用Array.unsafe_get堆来加速你的数组访问因为你可以确定我总是在数组的有效范围内的上面的例子。 (哦,我们还需要开始> = 0检查)。
let find_free_next heap start =
for i = start to ((Array.length heap)-1) do
match heap.(i) with
Hdr (Free (h), g) ->
i
done
How can i return the index of a loop as an integer once the match has been found?
If you want to stick to the imperative style, you can use an exception to exit the loop:
exception Found of int
let find_free_next heap start =
try
for i = start to Array.length heap - 1 do
match heap.(i) with
| Hdr (Free (h), g) -> raise (Found i)
| _ -> () (* If it is not what you are seeking *)
done;
raise Not_found
with
| Found n -> n
But generally, as ppl have already written, functional style is more preferred in OCaml:
let find_free_next heap start =
let len = Array.length heap in
let rec find i =
if i >= len then None
else
match heap.(i) with
| Hdr (Free h, g) -> Some i
| _ -> find (i+1)
in
find start
In this example, there is not much difference between the two versions, but use of exceptions for exiting loops/recursions must be used with caution; you can introduce control flow bugs pretty easily with them, and they are sometimes hard to debug.
BTW, you can use Array.unsafe_get heap i to speed up your array access since you can be sure that i is always in the valid range of the array the above examples. (Oh, we need start >= 0 check in addition, though.)
这篇关于如何返回OCaml中for循环的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!