As the error message indicates, you can use a ref
cell instead:
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
This does exactly what your code would do if it were legal. The !
operator gets the value out of the ref cell and :=
assigns a new value. As to why this is required, it's because the semantics of capturing a mutable value by a closure have proven to be confusing; using a ref
cell makes things somewhat more explicit and less error-prone (see http://lorgonblog.wordpress.com/2008/11/12/on-lambdas-capture-and-mutability/ for further elaboration).