ループ: 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 式のカスタマイズされたバージョンを使用します。 詳細については、シーケンス非同期式タスク式およびコンピュテーション式に関するページを参照してください。

関連項目