可变变量'x'以无效方式使用。闭包不能捕获可变变量

时间:2014-06-26 19:42:46

标签: f#

我有几本书,但是当我处理我的F#问题时,我发现这里的语法有些困难。如果有人认为我不应该在这里提出这些问题并在预算上提出另一本书推荐,请告诉我。

以下是重现我的项目问题的代码

[<EntryPoint>]
let main argv = 
    let mutable x = 0

    let somefuncthattakesfunc v = ignore

    let c() = 
        let y = x
        ignore


    somefuncthattakesfunc (fun () -> (x <- 1))
    Console.ReadKey()
    0 // return an integer exit code

我收到以下编译错误

The mutable variable 'x' is used in an invalid way. Mutable variables cannot be captured by closures. Consider eliminating this use of mutation or using a heap-allocated mutable reference cell via 'ref' and '!'.

有任何线索吗?

2 个答案:

答案 0 :(得分:5)

正如错误所解释的那样,你无法关闭你正在做的可变变量:

let y = x

(fun () -> x = 1)

如果您需要变异,建议您使用ref

let x = ref 0

let somefuncthattakesfunc v = ignore

let c() = 
    let y = !x
    ignore

somefuncthattakesfunc (fun () -> x := 1)

答案 1 :(得分:2)

正如错误消息所说,闭包不能捕获可变变量,而是使用引用单元格:

let main argv = 
    let x = ref 0

    let somefuncthattakesfunc v = ignore

    let c() = 
        let y = !x
        ignore

    somefuncthattakesfunc (fun () -> x := 1)
    Console.ReadKey()
    0 // return an integer exit code

另见this answer