#5: Standard ML's `ref`

Tagged as challenge

Written on 2018-01-30

In Standard ML and similar languages, one is not able to mutate the bindings to values. It is not possible to do something like x = 1 followed by x = 2. Instead, a special purpose cell is allocated, called a ref, whose contents can be modified. In Standard ML, ref is defined by the following signature:

signature REF =
  sig
    type 'a ref

    (* create a ref containing a value*)
    val ref : 'a -> 'a ref

    (* retrieve the contents of this value *)
    val op ! : 'a ref -> 'a

    (* Change the value of the ref *)
    val op := : 'a ref * 'a -> unit
  end

Implement ref. In Scheme, the behavior of ref might be like so:

; create a
(define a (ref 9))
(set-ref! a 8)
(deref a) ; ==> 8

Unless otherwise credited all material copyright © 2010–2018 by Robert Smith