“while"循环在 F# 计算表达式中的作用是什么? [英] What is the role of `while`-loops in computation expressions in F#?
问题描述
如果您定义了 builder-object 的 While
方法,则可以在 计算表达式.While
方法的签名是:
If you define a While
method of the builder-object, you can use while
-loops in your computation expressions. The signature of the While
method is:
member b.While (predicate:unit->bool, body:M<'a>) : M<'a>
为了比较,For
方法的签名是:
For comparison, the signature of the For
method is:
member b.For (items:seq<'a>, body:unit->M<'a>) : M<'a>
您应该注意到,在 While
方法中,主体是一个简单类型,而不是 For
方法中的函数.
You should notice that, in the While
-method, the body is a simple type, and not a function as in the For
method.
您可以在计算表达式中嵌入一些其他语句,例如 let
和函数调用,但这些语句不可能在 while
循环中多次执行.
You can embed some other statements, like let
and function-calls inside your computation-expressions, but those can impossibly execute in a while
-loop more than once.
builder {
while foo() do
printfn "step"
yield bar()
}
为什么 while
循环不执行多次,而只是重复执行?为什么与 for 循环有显着差异?更好的是,是否有一些在计算表达式中使用 while 循环的预期策略?
Why is the while
-loop not executed more than once, but merely repeated? Why the significant difference from for-loops? Better yet, is there some intended strategy for using while-loops in computation-expressions?
推荐答案
如果你看看 如何计算计算表达式,你会看到
If you look at how computation expressions are evaluated, you'll see that
while foo() do
printfn "step"
yield bar()
被翻译成类似的东西
builder.While(fun () -> foo(),
builder.Delay(fun () ->
printfn "step"
builder.Yield(bar()))))
这种翻译允许多次评估 while 循环的主体.虽然您的类型签名对于某些计算表达式(例如 seq
或 async
)是准确的,但请注意插入对 Delay
的调用可能会导致在不同的签名中.例如,您可以像这样定义一个列表构建器:
This translation allows the body of the while loop to be evaluated multiple times. While your type signatures are accurate for some computation expressions (such as seq
or async
), note that the insertion of the call to Delay
may result in a different signature. For instance, you could define a list builder like this:
type ListBuilder() =
member x.Delay f = f
member x.While(f, l) = if f() then l() @ (x.While(f, l)) else []
member x.Yield(i) = [i]
member x.Combine(l1,l2) = l1 @ l2()
member x.Zero() = []
member x.Run f = f()
let list = ListBuilder()
现在您可以计算如下表达式:
Now you can evaluate an expression like:
list {
let x = ref 0
while !x < 10 do
yield !x
x := !x + 1
}
得到相当于 [0 .. 9]
.
这里,我们的 While
方法具有签名 (unit -> bool) * (unit -> 'a list) ->'a list
,而不是 (unit -> bool) * 'a list ->'一个列表
.一般来说,当Delay
操作的类型为(unit -> M<'a>) ->D<M<'a>>
,While
方法的签名将是 (unit -> bool) * D<M<'a>>->M<'a>
.
Here, our While
method has the signature (unit -> bool) * (unit -> 'a list) -> 'a list
, rather than (unit -> bool) * 'a list -> 'a list
. In general, when the Delay
operation has type (unit -> M<'a>) -> D<M<'a>>
, the While
method's signature will be (unit -> bool) * D<M<'a>> -> M<'a>
.
这篇关于“while"循环在 F# 计算表达式中的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!