迴圈:while...do 運算式

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 運算式。 如需詳細資訊,請參閱序列非同步運算式工作運算式計算運算式

另請參閱