Ch.6 Introduction to ML programming

§ 6.13. Mutable memory reference types

ML has the following type constructor and primitives.

type 'a ref
val ref : 'a -> 'a ref
val ! : 'a ref -> 'a
val := : 'a ref * 'a -> unit

'a ref is a type of references (pointers) of type 'a. Function ref takes a value of type 'a and returns a reference to it. Function ! takes a reference and returns the value of that reference. Function := assigns a given value to a given reference. This destructively update the reference cell. The following shows an interactive session manipulating a reference.

#val x = ref 1;
val x = _ : int ref
# !x;
val it = 1 : int
# x := 2;
val it = () : unit
# !x;
val it = 2 : int

A function performing imperative operation can be written by maintaining a state using a reference.