F#从while循环中断 [英] F# break from while loop
问题描述
有什么办法可以像 C / C#
一样吗?
There is any way to do it like C/C#
?
例如(C#样式)
for( int i=0; i<100; i++)
{
if(i==66)
break;
}
推荐答案
简短的回答是否。通常,您将使用一些高阶函数来表示相同的功能。有许多功能可以让您执行此操作,这些功能对应于不同的模式(因此,如果您确切描述您的需求,那么有人可能会为您提供更好的答案)。
The short answer is no. You would generally use some higher-order function to express the same functionality. There is a number of functions that let you do this, corresponding to different patterns (so if you describe what exactly you need, someone might give you a better answer).
例如, tryFind
函数从给定谓词返回 true
的序列中返回第一个值,从而可以编写像这样的东西:
For example, tryFind
function returns the first value from a sequence for which a given predicate returns true
, which lets you write something like this:
seq { 0 .. 100 } |> Seq.tryFind (fun i ->
printfn "%d" i
i=66)
实际上,如果要表达一些高级逻辑并且有一个对应的函数,这是最好的方法。如果您确实需要表达诸如 break
之类的内容,则可以使用递归函数:
In practice, this is the best way to go if you are expressing some high-level logic and there is a corresponding function. If you really need to express something like break
, you can use a recursive function:
let rec loop n =
if n < 66 then
printfn "%d" n
loop (n + 1)
loop 0
一个更奇特的选择(虽然效率不高,但对DSL来说可能很好)是,您可以定义一个计算表达式,让您编写 break
和继续
。 这里是一个例子,但是正如我所说,这并不那么有效。
A more exotic option (that is not as efficient, but may be nice for DSLs) is that you can define a computation expression that lets you write break
and continue
. Here is an example, but as I said, this is not as efficient.
这篇关于F#从while循环中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!