Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encapsulating mutable states

Tags:

f#

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.

like image 207
steven Avatar asked Dec 15 '22 01:12

steven


1 Answers

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
like image 151
Daniel Avatar answered Jan 01 '23 10:01

Daniel