Continuations in D?
    David Medlock 
    noone at nowhere.com
       
    Mon Feb 20 07:36:04 PST 2006
    
    
  
Unknown W. Brackets wrote:
> Please forgive my ignorance; what is a continuation or where can I read 
> about it?
> 
> Thanks,
> -[Unknown]
> 
> 
>> Does D support continuations?  I anticipate that continuations will 
>> become
>> increasingly important as people seek ways to retain the simplicity of 
>> a threaded architecture while
>> avoiding the overhead of actual threads.  If D could support this 
>> language feature, I think it would make D very
>> appealing for a whole variety of applications.
>>
>> Ian.
>>
>>
To my knowledge of them, they are an alternate form of writing code.
Consider a function which returns an integer:
int foo() { return 1; }
Now suppose you wanted to return multiple integers:
int foo() { return 2; return 3; return 4; } // doesnt work
to do this requires an inversion of control, the called function will 
call you back with the values:
void foo( void delegate( int ) yield )
{
   yield( 2 );
   yield( 3 );
   yield( 4 );
}
This is commonly known as continuation passing style or CPS.  In this 
style the function passed to a function represents the 'rest of the 
program'.  In this way the function can complete the program more than 
one, hence a continuation of the current program.
Converting the code to this form allows you to use pieces of code in 
various ways.  Consider try/catch.
try
{
   calc1();
   calc2();
}
catch( ... ) { ..various fail code... }
Using this you can see the conversion of this to CPS form:
void failure_code() { ..various fail code... }
void try_function( void delegate() failure )
{
   if ( calc1 == FAIL ) failure();
   else if ( calc2 == FAIL ) failure();
}
try_function( &failure_code )
Inner functions in D make this style of code very workable.
PS. Note that with an appropriate return value from failure() you can 
signify that the failed calculation be retried!
This is a simplification but if you google there are several good papers 
on them.
-DavidM
    
    
More information about the Digitalmars-d
mailing list