# The Ref structure

## ________ Synopsis ____________________________________________________

```    signature REF
structure Ref : REF
```

Common operations on references.

The type ref and its constructor, as well as the functions !, := and :=: are available in the top-level environment.

## ________ Import ______________________________________________________

Imported implicitly.

## ________ Interface ___________________________________________________

```    signature REF =
sig
datatype ref = datatype ref
type  'a t   = 'a ref

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

val app :      ('a -> unit) -> 'a ref -> unit
val map :      ('a -> 'b) -> 'a ref -> 'b ref
val modify :   ('a -> 'a) -> 'a ref -> unit

val equal :    'a ref * 'a ref -> bool
end
```

## ________ Description _________________________________________________

datatype 'a ref = ref of 'a
type t = ref

The type of mutable references.

! re

Returns the value referred to by re.

re := a

Makes the reference re refer to value a.

re1 :=: re2

Swaps the values referred to by the references re1 and re2.

exchange (re, a)

Makes the reference re refer to value a and returns the previously referred to value in a single atomic operation. This function can be used to program mutexes and similar locking mechanisms.

app f re

Applies the function f to the value referred to by the reference re. Equivalent to f (!re).

map f re

Creates a new reference that refers to the value f a, where a is the value referred to to by re. Equivalent to ref (f (!re)).

modify f re

Makes the reference re refer to the value f a, where a is the value previously referred to. Note that this is not an atomic operation, since f might perform arbitrary computations. As long as no unconditional assignments are performed in between, it is guaranteed that no thread can access the value referred to before the operation completes, however. The reference refers to a future of f a until that point. Ignoring concurrency issues, the above expression is equivalent to re := f (!re).

equal (re1, re2)

An explicit equality function on references. Equivalent to op=.