循环:while...do 表达式 (F#)

while...do 表达式用于在指定的测试条件为 true 时,执行迭代循环。

while test-expression do
   body-expression

备注

计算 test-expression,如果计算结果为 true,则执行 body-expression,然后再次计算测试表达式。 body-expression 必须具有 unit 类型。 如果测试表达式为 false,则迭代结束。

下面的示例阐释了 while...do 表达式的用法。

open System

let lookForValue value maxValue =
  let mutable continueLooping = true
  let randomNumberGenerator = new Random()
  while continueLooping do
    // Generate a random number between 1 and maxValue.
    let rand = randomNumberGenerator.Next(maxValue)
    printf "%d " rand
    if rand = value then 
       printfn "\nFound a %d!" value
       continueLooping <- false

lookForValue 10 20

以上代码的输出是一个介于 1 和 20 之间的随机数字流,最后一个数字为 10。

13 19 8 18 16 2 10
Found a 10!

备注

可在序列表达式和其他计算表达式中使用 while...do,这种情况下将使用 while...do 表达式的自定义版本。有关更多信息,请参见序列 (F#)异步工作流 (F#)计算表达式 (F#)

请参见

参考

循环:for...in 表达式 (F#)

循环:for...to 表达式 (F#)

其他资源

F# 语言参考