Function return with closure

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, here we see that f1 and f2 are one and the same function, since they obviously use the same instance of "counter".

Expected Result:

 1 2 1 2 

QUESTION: Should f1 and f2 be two separate instances? In the end, they are created by two different calls to "CreateFunc" ???

thanks

+6
source share
1 answer
 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.

+8
source

Source: https://habr.com/ru/post/901010/


All Articles