循环:while...do 表达式

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

语法

while test-expression do
    body-expression

备注

计算测试表达式;如果为 true,则执行主体表达式,并再次计算测试表达式。 主体表达式必须具有类型 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 表达式。 有关详细信息,请参阅序列异步表达式任务表达式计算表达式

另请参阅