Probably another dumb F# beginner's question... But it's bugging me all the same
I can't seem to find any answers to this online... might be 'cause I search the wrong terms but eh
anyway my code goes as follows:
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 is telling me that x
is used in an invalid way, that mutable variables can't be captured by closures
why is that? and what can I do to allow me to mutate it?
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).