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())
Exit
1 2 1 2
Explanation:
In your original solution, CreateFunc was a function, but always the same function ( CreateFunc , f1 and f2 were synonyms, all pointing to the same function). In my solution, CreateFunc is a function that returns the new function whenever it is called, so each function has its own state (i.e. counter ).
In short: the original CreateFunc was a value, always the same value.
source share