我有几本书,但是当我正在处理我的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
Run Code Online (Sandbox Code Playgroud)
我收到以下编译错误
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 '!'.
Run Code Online (Sandbox Code Playgroud)
任何线索?
正如错误所解释的那样,您无法关闭正在执行的可变变量:
let y = x
Run Code Online (Sandbox Code Playgroud)
和
(fun () -> x = 1)
Run Code Online (Sandbox Code Playgroud)
它建议你使用a ref代替你需要变异:
let x = ref 0
let somefuncthattakesfunc v = ignore
let c() =
let y = !x
ignore
somefuncthattakesfunc (fun () -> x := 1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
214 次 |
| 最近记录: |