I'm working my way through the F# Wikibook and I have got to the section on reference cells, in which the following code snippet appears:
let incr =
let counter = ref 0
fun () ->
counter := !counter + 1
!counter;;
This function is then called three times, giving the values 1, 2, and 3 respectively. Can someone please explain why this function does not return 1 each time it is called? The way I interpret this code (which is obviously not the correct interpretation, hence the question) is that, first, the reference cell 'counter' is declared, with contents equal to 0
, then the contents of 'counter' is incremented by 1 and then dereferenced using the anonymous function. Since each call of incr();;
declares 'counter' with contents 0
, I don't understand why calling incr();;
doesn't simply return 1 each time.
Can anyone correct my understanding?
Thanks in advance.
Think of it this way: incr
is a value, not a function. Its value is a closure that captures some state (i.e., counter
). It's the closure that is subsequently being called potentially multiple times (incr
is only executed/assigned once). Maybe seeing the equivalent C# would help.
static Func<int> MakeCounter() {
int counter = 0;
return () => {
counter++;
return counter;
};
}
var incr = MakeCounter();
incr(); //1
incr(); //2
incr(); //3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With