[MLton] Monadic MLton.Vector.create with update using Primitive.Array

Vesa Karvonen vesa.karvonen@cs.helsinki.fi
Wed, 29 Mar 2006 13:22:43 +0300


Here is the interface:

      type ('a, 'e) m

      val createM : int * (int -> ('e, 'e) m) -> 'e vector

      val return : 'e -> ('e, 'e) m
      val >>= : ('a, 'e) m * ('a -> ('b, 'e) m) -> ('b, 'e) m

      val subM : int -> ('e, 'e) m
      val updateM : int * 'e -> (unit, 'e) m

And here is the implementation:

      type ('a, 'e) m = int * 'e array -> 'a

      fun createM (n, f) =
          let val a = Primitive.Array.array n
          in Util.naturalForeach
                (n, fn i => Primitive.Array.update (a, i, f i (i, a)))
           ; fromArray a
          end

      fun return x _ = x
      fun (mA >>= a2mB) na = a2mB (mA na) na
      fun subM i (n, a) =
          if Primitive.safe andalso Primitive.Int.geu (i, n) then
             raise Subscript
          else
             Primitive.Array.sub (a, i)
      fun updateM (i, e) (n, a) =
          if Primitive.safe andalso Primitive.Int.geu (i, n) then
             raise Subscript
          else
             Primitive.Array.update (a, i, e)

It would be interesting to know how this compares performance wise to
the non-monadic approach.  (I must get back to work.)

-Vesa Karvonen