2014-06-26 66 views
1

我有幾本書,但是由於我正在處理我的F#問題,因此我在這裏找到了一些語法上的困難。如果有人認爲我不應該在這裏問這些問題,並有另一個預算的書推薦,請讓我知道。可變變量'x'以無效方式使用。可變變量不能通過關閉來捕獲

下面是重現該問題的代碼,我用我的項目有

[<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

使用'ref'而不是'mutable',但你永遠不會分配給'x',那爲什麼它是可變的辦法? – ildjarn

+0

@ildjarn我分配給lambda表達式中的x – fahadash

+3

不,你正在比較'x' - 賦值是'<-'。 ; - ] – ildjarn

回答

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

+0

我在lambda表達式中錯誤地將=而不是< - 賦值運算符。我已糾正它。現在這個解決方案不起作用。它說x不可變。 – fahadash

+1

@fahadash代碼更新! – Gustavo

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)