ループ: for...to 式

for...to 式は、ループでループ変数の値の範囲を繰り返し処理するために使用されます。

構文

for identifier = start [ to | downto ] finish do
    body-expression

解説

識別子の型は、start および finish 式の型から推論されます。 これらの式の型は、32 ビットの整数である必要があります。

技術的には式ですが、for...to は、命令型プログラミング言語では従来のステートメントに似ています。 body-expression の戻り値の型は unit である必要があります。 次に、for...to 式のさまざまな使用例を示します。

// A simple for...to loop.
let function1() =
  for i = 1 to 10 do
    printf "%d " i
  printfn ""

// A for...to loop that counts in reverse.
let function2() =
  for i = 10 downto 1 do
    printf "%d " i
  printfn ""

function1()
function2()

// A for...to loop that uses functions as the start and finish expressions.
let beginning x y = x - 2*y
let ending x y = x + 2*y

let function3 x y =
  for i = (beginning x y) to (ending x y) do
     printf "%d " i
  printfn ""

function3 10 4

このコードの出力は、次のようになります。

1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

関連項目