[MLton-user] SMLofNJ.Cont.isolate

Matthew Fluet fluet at tti-c.org
Tue Apr 22 19:21:22 PDT 2008


On Tue, 22 Apr 2008, Dave Herman wrote:
> In SML/NJ there's a useful function for invoking a thunk in an empty 
> continuation, called SMLofNJ.Cont.isolate. If I'm not mistaken, this isn't 
> too difficult to implement. Is this something that could be added to MLton?

I can't make sense of the isolate description 
(http://www.smlnj.org/doc/SMLofNJ/pages/cont.html); the types don't seem 
to work out:

  val isolate : ('a -> unit) -> 'a cont
  isolate f x
     Discard all live data from the calling context (except what is
     reachable from f or x), then call f(x), then exit. This may use much
     less memory then something like f(x) before exit().

I think what they really mean is that if
   val c = isolate f
then throw c x discards all live data ....

I'm sure it is possible to implement isolate simply in terms of callcc, 
though it may not have the desired space behavior.

With the MLton.Thread structure (different from the Primitive.MLton.Thread 
structure referenced in <src>/basis-library/mlton/cont.sml), you could get 
the behavior of 'throw (isolate f) x' with the following:

fun isolateAndThrow (f: 'a -> unit) (x: 'a) : 'b =
   let
     val t = MLton.Thread.new f
     val r = MLton.Thread.prepare (t, x)
   in
     MLton.Thread.switch (fn _ => r)
   end

In the MLton.Cont structure, we have
   type 'a t = (unit -> 'a) -> unit

So it seems we could implement isolate as:

fun isolate (f: 'a -> unit) : 'a cont =
   fn x =>
   let
     val t = MLton.Thread.new (f o x)
     val r = MLton.Thread.prepare (t, ())
   in
     MLton.Thread.switch (fn _ => r)
   end

All untested.  And you need to call OS.Process.exit if the isolated 
function returns normally (or exceptionally).  And I'm not 100% sure that 
threads and continuations play nice together, but the above seems fairly 
benign.




More information about the MLton-user mailing list