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

时间:2009-09-26 06:31:51

标签: 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 '!' 

代码:

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

为什么不让我打印变量?

1 个答案:

答案 0 :(得分:17)

你不能在闭包中引用mutable,并且包括seq {}和async {}块之类的构造。

你可以写

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

有关讨论,请参阅this blog