1

I have a couple of books that I am going by, but as I am working on my F# problems, I find some difficulties in syntax here. If anyone thinks I should not be asking these questions here and have another book recommendation on a budget, please let me know.

Here is the code that reproduces the problem I am having with my project

[<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

I am getting the following compile error

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 '!'.

Any clue ?

fahadash
  • 3,133
  • 1
  • 30
  • 59

2 Answers2

5

As the error explains, you can't close over mutable variables, which you are doing in:

let y = x

and

(fun () -> x = 1)

It suggests you use a ref instead if you need mutation:

let x = ref 0

let somefuncthattakesfunc v = ignore

let c() = 
    let y = !x
    ignore

somefuncthattakesfunc (fun () -> x := 1)
Lee
  • 142,018
  • 20
  • 234
  • 287
2

As the error message says, mutable variables cannot be captured by closures, use a reference cell instead:

let main argv = 
    let x = ref 0

    let somefuncthattakesfunc v = ignore

    let c() = 
        let y = !x
        ignore

    somefuncthattakesfunc (fun () -> x := 1)
    Console.ReadKey()
    0 // return an integer exit code

Also see this answer.

Community
  • 1
  • 1
Gus
  • 25,839
  • 2
  • 51
  • 76
  • I mistakenly put = instead of <- assignment operator in lambda expression. I have corrected it. Now this solution does not work. It says x is not mutable. – fahadash Jun 26 '14 at 20:04