Category:Continuation

From Rosetta Code
Library
This is an example of a library. You may see a list of other libraries used on Rosetta Code at Category:Solutions by Library.

Ruby 1.9 moved the method Kernel#callcc and the class Continuation from the core language to a standard library. Starting with Ruby 1.9, programs that use these features must require 'continuation'.

<lang ruby># This code works with both Ruby 1.8 and Ruby 1.9. require 'continuation' unless defined? Continuation</lang>

Most Ruby programs will never use this library.

  1. MRI has a slow implementation of continuations.
  2. Continuations make spaghetti code with very confusing control flow.



Kernel#callcc creates a continuation. Continuation#call, also known as Continuation#[], continues the program from the place that called Kernel#callcc. With a continuation, you can continue a function call after it ends.

<lang ruby>def f

 puts "1st line of output"
 callcc { |cc| return cc }  # f ends with a return...
 puts "3rd line of output"
 return nil

end

cont = f if cont

 puts "2nd line of output"
 cont.call                  # ...but this continues f

end</lang>

Kernel#callcc from Ruby is like call-with-current-continuation from Scheme, and almost like setjmp from C, except that setjmp saves less information. (With setjmp, you must not continue a function call after it ends, because C frees the stack frame when it ends.)

Pages in category "Continuation"

The following 4 pages are in this category, out of 4 total.