Ele*_*fee 2 variables f# function mutable mutation
可能是另一个愚蠢的F#初学者的问题...但是它一直困扰着我
我似乎无法在网上找到任何答案...可能是'因为我搜索错误的条款,但是呃
无论如何我的代码如下:
let counter() =
let mutable x = 0
let increment(y :int) =
x <- x + y // this line is giving me trouble
printfn "%A" x // and this one too
increment // return the function
Run Code Online (Sandbox Code Playgroud)
Visual Studio告诉我,x以无效的方式使用,闭包不能捕获可变变量
这是为什么?我能做些什么来让我改变它?
如错误消息所示,您可以使用ref单元格:
let counter() =
let x = ref 0
let increment(y :int) =
x := !x + y // this line is giving me trouble
printfn "%A" !x // and this one too
increment // return the function
Run Code Online (Sandbox Code Playgroud)
这完全符合您的代码在合法时所做的事情.该!运营商得到值出裁判细胞,并:=赋予了新的价值.至于为什么需要这样做,这是因为闭包捕获可变值的语义已被证明是混乱的; 使用ref单元格可以使事情更明确,更不容易出错(请参阅http://lorgonblog.wordpress.com/2008/11/12/on-lambdas-capture-and-mutability/进一步详细说明).