ref.mlw 1.08 KB
Newer Older
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
1 2 3 4 5 6 7 8 9

(* References.

   A mutable variable, or ``reference'' in ML terminology, is simply a
   record with a single mutable field 'contents'.

   Creation, access, and assignment are provided as 'ref', prefix '!', and
   infix ':=', respectively.
*)
10 11 12 13 14

module Ref

  type ref 'a = {| mutable contents : 'a |}

Andrei Paskevich's avatar
Andrei Paskevich committed
15
  function (!) (x: ref 'a) : 'a = x.contents
16

17
  let ref (v: 'a) = {} {| contents = v |} { result = {| contents = v |} }
18

19
  let (!) (r:ref 'a) = {} r.contents { result = !r }
20

21
  let (:=) (r:ref 'a) (v:'a) = {} r.contents <- v { !r = v }
22 23 24

end

Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
25 26
(* Module Refint adds a few operations specific to integer references. *)

27 28 29 30 31
module Refint

  use export int.Int
  use export module Ref

32 33 34
  let incr (r: ref int) = {} r := !r + 1 { !r = old !r + 1 }
  let decr (r: ref int) = {} r := !r - 1 { !r = old !r - 1 }

Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
35 36 37
  let (+=)   (r: ref int) (v: int) = {} r := !r + v { !r = old !r + v }
  let (-=)   (r: ref int) (v: int) = {} r := !r - v { !r = old !r - v }
  let ( *= ) (r: ref int) (v: int) = {} r := !r * v { !r = old !r * v }
38 39

end
40 41 42 43 44 45

(*
Local Variables:
compile-command: "unset LANG; make -C .. modules/ref"
End:
*)