OCaml references
In OCaml, a reference is a mutable cell that can hold a single value of any type. References are a way to introduce imperative programming into an otherwise functional language. They are created using the ref keyword, which takes an initial value as an argument. You can access the value in a reference using the ! operator, and you can modify the value in a reference using the := operator.
Here is an example of using a reference to implement a simple counter:
let counter = ref 0
let increment_counter () = counter := !counter + 1
let get_counter () : int = !counter
get_counter () ;;
- : int = 0
increment_counter () ;;
- : unit = ()
get_counter () ;;
- : int = 1
In this example, we define a reference counter that holds an integer value of 0. We also define two functions: increment_counter, which increments the value of counter, and get_counter, which returns the current value of counter.
When we call increment_counter, the !counter expression is evaluated to get the current value of the counter reference, which is then incremented by 1 using the + operator. The result of this expression is then assigned to the counter reference using the := operator, which updates the value of the reference.
We can use get_counter to retrieve the current value of the counter reference at any time.