What is the role of `while`-loops in computation expressions in F#?
- by MizardX
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 comparison, the signature of the For method is:
member b.For (items:seq<'a>, body:unit->M<'a>) : M<'a>
You should notice that, in the While-method, the body is a simple type, and not a function as in the For method.
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()
}
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?