Question

# let counter () = 
    let c = ref 0 in 
    fun () -> 
      let _ = c := !c + 1 in 
      !c ;; 
val counter : unit -> unit -> int = <fun> 

# let incCounter = counter () ;; 

# incCounter () ;; 
- : int = 1 

# incCounter () ;; 
- : int = 2 

I do not understand why the line let c = ref 0 doesn't get called again every time you call incCounter () ;;. It seems like the part fun() ->... just works on one reference of c each time you call incCounter.

Was it helpful?

Solution

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.

OTHER TIPS

That's correct. Each time you call a particular function value, the same reference cell will be accessed. If you call counter again, you'll get a different function value that accesses a different reference cell.

Incidentally, incr c is a clearer way to express let _ = c := c + 1 in ....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top