[MLton] Monadic MLton.Vector.create

Vesa Karvonen vesa.karvonen@cs.helsinki.fi
Wed, 29 Mar 2006 01:08:14 +0300


Quoting Henry Cejtin <henry.cejtin@sbcglobal.net>:
[...]
> The only ugliness to me in the create proposal is the fact  that  update  and
> sub might be squirreled away, so you have to make them raise Fail if they are
> called after create returns.  It would be nice if one could make it  so  that
> they  couldn't  be  in scope or saved any where, but I don't see any way that
> isn't REALLY convoluted and ugly.
[...]

Were you thinking about monads?  Here is a suitable signature for create:

signature CREATE =
   sig
      type 'a m

      val create : int -> (int -> 'a m) -> 'a vector

      val >>= : 'a m * ('a -> 'b m) -> 'b m
      val return : 'a -> 'a m
      val sub  : int -> 'a m
      val update : int * 'b -> unit m
   end

The below functor implements the same fib function as in Stephen's
earlier post.

functor Fib (C : CREATE) =
   struct
      local
         open C
         infix >>=
      in
      fun fib i =
          create i (fn i =>
                       if i <= 1 then
                          return i
                       else
                          sub (i-1) >>= (fn x =>
                          sub (i-2) >>= (fn y =>
                          return (x+y))))
      end
   end

I wouldn't call it "ugly", but YMMV.

-Vesa Karvonen