3

可能是另一个愚蠢的 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

Visual Studio 告诉我,x它的使用方式无效,闭包无法捕获可变变量

这是为什么?我能做些什么来让我变异它?

4

1 回答 1

9

如错误消息所示,您可以改用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

如果它是合法的,这正是你的代码会做的事情。!操作员从 ref 单元格中获取值并分配:=一个新值。至于为什么需要这样做,这是因为通过闭包捕获可变值的语义已被证明是令人困惑的;使用ref单元格使事情更加明确且不易出错(请参阅http://lorgonblog.wordpress.com/2008/11/12/on-lambdas-capture-and-mutability/以获得进一步的详细说明)。

于 2013-04-23T19:39:01.193 回答