13 Refs

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:

We can bind them to names:

Refs are created with the standard library function ref.

This is a reference to in integer, whose current contents are 3110. Let's bind it to a name.

So what is y bound to right now?

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").

Note that when we dereference y, we get an int, not an int ref.

This doesn't type check, because y is a ref, and x is an int. We need to bang y to do this.

We can use the assignment operator to change the value of y.

Note that the assignment operator returns a unit.

Now, y points to the same location, but with different contents (2110). We can show this by banging y again.

We can't assign a different type to y, only integers.