循环:for...to 表达式

for...to 表达式用于循环访问循环变量的一系列值。

语法

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

注解

标识符的类型从 开始 表达式和 完成 表达式的类型推断。 这些表达式的类型必须为 32 位整数。

虽然从技术上讲是表达式, for...to 但更像是命令性编程语言中的传统语句。 正文表达式的返回类型必须是 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

另请参阅