在 SMLofNJ.Cont 隔离

isolate in SMLofNJ.Cont

我正在阅读标准 ML 中的 continuationsSMLofNJ.Cont). I understood what callcc and throw does, but could not understand isolate。文档说

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().

然而这对我来说没有任何意义。我只是想通过一些示例了解此功能的作用。

MLton 使用 callccthrow:

isolate 做得更好 explaining an implementation
val isolate: ('a -> unit) -> 'a t =
  fn (f: 'a -> unit) =>
  callcc
  (fn k1 =>
   let
      val x = callcc (fn k2 => throw (k1, k2))
      val _ = (f x ; Exit.topLevelSuffix ())
              handle exn => MLtonExn.topLevelHandler exn
   in
      raise Fail "MLton.Cont.isolate: return from (wrapped) func"
   end)

We use the standard nested callcc trick to return a continuation that is ready to receive an argument, execute the isolated function, and exit the program. [...]

该页面继续解释如何以更少的 space 泄漏实现相同的效果。

MLton's CONT signature has a different documentation line than SML/NJ's CONT signature:

  • isolate f creates a continuation that evaluates f in an empty context.

    This is a constant time operation, and yields a constant size stack.