OCaml By Examples

mutability

utop

Variables are not mutable by default in OCaml, they are just re-declared (or shadowed).
utop # let a =
    let b = 5 in 
    let b = 5 + b in 
    b;;
val a : int = 10
Some OCaml types allow mutability. For example, `arrays` and `bytes`. Records also allow some of their fields to be modified by declaring them with the `mutable` keywords.
utop # type bus = { mutable passengers : int };;
type bus = { mutable passengers : int; }
You can then modify them with the mutation token [`<-`](https://www.craigfe.io/operator-lookup/?q=%3C-).
utop # let shuttle = { passengers = 0 };;
val shuttle : bus = {passengers = 0}

utop # shuttle.passengers <- 3;;
- : unit = ()

utop # shuttle;;
- : bus = {passengers = 3}
While you can wrap your mutable variables into records, it can get tedious. OCaml offers some syntaxic sugar that does that for you with the `ref` keyword.
utop # let counter = ref 0;;
val counter : int ref = {contents = 0}
A ref can then be mutated with the reference assignment operator [`:=`](https://www.craigfe.io/operator-lookup/?q=%3A%3D).
utop # counter := 3;;
- : unit = ()

utop # counter;;
- : int ref = {contents = 3}
To access a ref's content, just use the dereferencing operator [`!`](https://www.craigfe.io/operator-lookup/?q=%21).
utop # !counter + 4;;
- : int = 7
But remember, under the hood a ref is just a record with a mutable field, as well as some re-define operators to facilitate manipulation of the mutable field.
utop # type 'a ref = { mutable contents : 'a }
let (:=) r v = r.contents <- v
let (!) r = r.contents;;
type 'a ref = { mutable contents : 'a; }
val ( := ) : 'a ref -> 'a -> unit = <fun>
val ( ! ) : 'a ref -> 'a = <fun>
next: recursion