A reference in OCaml is a pointer to a typed location in memory. This is also called a "ref" or a "ref cell"
The binding of the variable to the pointer is immutable, but the contents of the memory location are mutable.
Recall immutable values in OCaml.
We can have ints:
3110;;
- : int = 3110
We can bind them to names:
let x = 3110;;
val x : int = 3110
Refs are created with the standard library function ref.
ref 3110;;
- : int ref = {contents = 3110}
This is a reference to in integer, whose current contents are 3110. Let's bind it to a name.
let y = ref 3110;;
val y : int ref = {contents = 3110}
So what is y bound to right now?
y;;
- : int ref = {contents = 3110}
It's a location in memory with the contents 3110. If we want to get the contents out, we can use the dereference operator, ! (pronounced "bang").
!y;;
- : int = 3110
Note that when we dereference y, we get an int, not an int ref.
x + y;;
File "[7]", line 1, characters 4-5:
1 | x + y;;
^
Error: This expression has type int ref
but an expression was expected of type int
This doesn't type check, because y is a ref, and x is an int. We need to bang y to do this.
x + !y;;
- : int = 6220
We can use the assignment operator to change the value of y.
y := 2110;;
- : unit = ()
Note that the assignment operator returns a unit.
y;;
- : int ref = {contents = 2110}
Now, y points to the same location, but with different contents (2110). We can show this by banging y again.
x + !y;;
- : int = 5220
y := "Hello";;
File "[12]", line 1, characters 5-12:
1 | y := "Hello";;
^^^^^^^
Error: This expression has type string but an expression was expected of type
int
We can't assign a different type to y, only integers.