[MLton-user] SMLofNJ.Cont.isolate

Matthew Fluet fluet at tti-c.org
Fri Apr 25 13:52:16 PDT 2008


On Fri, 25 Apr 2008, Dave Herman wrote:
> Maybe you meant this:
>
>     fun isolate (f: 'a -> unit) : 'a cont =
>       fn x =>
>       let
>         fun g () = (f x; OS.Process.exit OS.Process.success)
>         val t = MLton.Thread.new g
>         val r = MLton.Thread.prepare (t, ())
>       in
>         MLton.Thread.switch (fn _ => r)
>       end
>
> Yes?

Pretty close.  You should handle both normal and exceptional returns from 
the isolated computation, and to properly match the MLton.Cont interface, 
the argument x is of type unit -> 'a, to be run in the thrown-to context 
(though, in the isolate case, the thrown-to context is empty).  So, 
something like:

   fun isolate (f: 'a -> unit) : 'a cont =
     fn (x : unit -> 'a) =>
     let
        fun g () = (f (x ()); OS.Process.exit OS.Process.success)
                   handle _ => OS.Process.exit OS.Process.failure
        val t = MLton.Thread.new g
        val r = MLton.Thread.prepare (t, ())
     in
       MLton.Thread.switch (fn _ => r)
     end

If you are interested in efficiency, you might consider specializing the 
MLton.Thread.{new,preopare,switch} implementation for the isolate case. 
(For example, you only ever have New threads, never Dead, Interrupted, or 
Paused.)



More information about the MLton-user mailing list