www.delorie.com/gnu/docs/kawa/kawa-tour_19.html   search  
 
Buy GNU books!


Kawa: Compiling Scheme to Java

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.18 Continuations

Scheme continuations "capture" the current execution state. They can be implemented by copying the stack, but this requires non-portable native code. Kawa continuations are implemented using Java exceptions, and can be used to prematurely exit (throw), but not to implement co-routines (which should use threads anyway).

 
class callcc extends Procedure1 {
  public Object apply1 (Object arg1)
  {
    Procedure proc = (Procedure) arg1;
    Continuation cont = new Continuation ();
    try { return proc.apply1(cont); }
    catch (CalledContinuation ex)
      {
        if (ex.continuation != cont)
             throw ex;  // Re-throw.
        return ex.value;
      }
  }
  ...
}

This is the Procedure that implements call-with-current-continuation. It creates cont, which is the "current continuation", and passes it to the incoming proc. If callcc catches a CalledContinuation exception it means that proc invoked some Continuation. If it is "our" continuation, return the value passed to the continuation; otherwise re-throw it up the stack until we get a matching handler. (I have left out code to detect unsupported invocation of cont after callcc returns.)

 
class Continuation extends Procedure1 {
  public Object apply1 (Object arg1)
  {
    throw new CalledContinuation (arg1, this);
  }
  ...
}

A Continuation is the actual continuation object that is passed to callcc's argument; when it is invoked, it throws a CalledContinuation that contains the continuation and the value returned.

 
class CalledContinuation extends RuntimeException {
  Object value;
  Continuation continuation;
  CalledContinuation (Object value, Continuation continuation)
  {
    super ("call/cc called");
    this.value = value;
    this.continuation = continuation;
  }
  ...
}

CalledContinuation is the exception that is thrown when the continuation is invoked.


  webmaster   donations   bookstore     delorie software   privacy  
  Copyright © 2003   by The Free Software Foundation     Updated Jun 2003