The line let c = ref 0
gets called everytime when counter
is called (and not everytime incCounter
is called).
The type of counter
is unit -> unit -> int
, meaning that counter ()
returns a function of type unit -> int
. If we say let incCounter = counter ()
, we obtain a newly created function of type unit -> int
. This function, in turn, modifies a reference that was constructed before by the call counter ()
.
That said, the purpose of counter ()
is to construct a new counter that can afterwards be incremented.