The following code:
let CreateFunc=
let counter = ref 0
fun () -> counter := !counter + 1; !counter
let f1 = CreateFunc
let f2 = CreateFunc
printfn "%d" (f1())
printfn "%d" (f1())
printfn "%d" (f2())
printfn "%d" (f2())
Outputs:
1
2
3
4
So, basically, what we see here is f1 and f2 being the same function – as they’re obviously sharing the same instance of ‘counter’.
The expected output is:
1
2
1
2
QUESTION: Shouldn’t f1 and f2 be two separate instances? After all they are created by the two different calls to ‘CreateFunc’???
Thanks
Output is
Explanation:
In your original solution,
CreateFuncwas a function, but always the same function (CreateFunc,f1andf2were all synonyms, all pointing to the same function). In my solutionCreateFuncis a function which returns a new function whenever it is called, thus each function has its own state (i.e.counter).In short: the original
CreateFuncwas a value, always the same value.