可变变量'i'以无效方式使用.

RCI*_*CIX 9 f#

我试图在F#中编写一些简单的代码,我得到这个错误:

Error   1   The mutable variable 'i' is used in an invalid way. Mutable variables may not be captured by closures. Consider eliminating this use of mutation or using a heap-allocated mutable reference cell via 'ref' and '!' 
Run Code Online (Sandbox Code Playgroud)

码:

let printProcess = async {
        let mutable i = 1;
        while true do
            System.Console.WriteLine(i);//error is here
            i <- i + 1;
    }
Run Code Online (Sandbox Code Playgroud)

为什么不让它打印变量?

Bri*_*ian 17

您不能在闭包内引用mutable,并且包括seq {}和async {}块等构造.

你可以写

let printProcess = async {
        let i = ref 1
        while true do
            System.Console.WriteLine(!i)
            i := !i + 1
    }
Run Code Online (Sandbox Code Playgroud)

有关讨论,请参阅此博客.

  • 为什么必须这样做的简短答案是堆栈上有'可变'值,而'ref'值在堆上.由于一旦函数退出所有可变值,堆栈帧将被清除.另一方面,Ref值将像任何其他垃圾收集对象一样持久存在. (6认同)
  • 另一种说法是F#捕获值而不是变量.因此,捕获可变变量的值与捕获不可变变量的值相同,因为值本身始终是不可变的.这种行为可能不是人们所期望的,因此被禁止. (3认同)