Module Ref


module Ref: Extlib.Ref
Operations on references.

References are mutable values, i.e. "variables" which may actually change value during their life-time, as variables in imperative languages. References can be understood as 1-cell arrays and are typically used to implement imperative algorithms in OCaml.

References are useful but don't abuse them.
Author(s): Xavier Leroy (base module), David Teller


type 'a t = 'a Standard.ref 
The type of references.
val ref : 'a -> 'a Standard.ref
Return a fresh reference containing the given value.
val (!) : 'a Standard.ref -> 'a
!r returns the current contents of reference r. Equivalent to fun r -> r.contents.
val (:=) : 'a Standard.ref -> 'a -> unit
r := a stores the value of a in reference r. Equivalent to fun r v -> r.contents <- v.
val set : 'a Standard.ref -> 'a -> unit
As :=
val get : 'a Standard.ref -> 'a
As !
val copy : 'a Standard.ref -> 'a Standard.ref
copy r returns a new reference with the same initial content as r.
val pre : 'a Standard.ref -> ('a -> 'a) -> 'a
Perform an operation on a reference and return the new value of that reference.

For instance, if x is a reference to 1, pre x ( ( + ) 1) returns 2 and sets x to 2.

val post : 'a Standard.ref -> ('a -> 'a) -> 'a
Perform an operation on a reference and return the previous value of that reference.

For instance, if x is a reference to 1, post x ( ( + ) 1) returns 1 and sets x to 2.

val swap : 'a Standard.ref -> 'a Standard.ref -> unit
swap a b puts !b in a and !a in b
val post_incr : int Standard.ref -> int
Increment an integer, return the old value.

Comparable to C or Java's i++.

val post_decr : int Standard.ref -> int
Decrement an integer, return the old value.

Comparable to C or Java 's i--.

val pre_incr : int Standard.ref -> int
Increment an integer, return the new value.

Comparable to C or Java's ++i.

val pre_decr : int Standard.ref -> int
Increment an integer, return the new value.

Comparable to C or Java's --i.

val protect : 'a Standard.ref -> 'a -> (unit -> 'b) -> 'b
Assign a reference temporarily.

protect r v body sets the value of r to v and executes body. Once body has been executed, whether termination happens as a consequence of regular evaluation or exception, the previous value of r is restored.


Boilerplate code


S-Expressions

val t_of_sexp : (Sexplib.Sexp.t -> 'a) -> Sexplib.Sexp.t -> 'a t
val sexp_of_t : ('a -> Sexplib.Sexp.t) -> 'a t -> Sexplib.Sexp.t

Printing

val print : (Extlib.InnerIO.input -> 'a -> unit) ->
Extlib.InnerIO.input -> 'a t -> unit