Class Continuation
In: lib/extensions/continuation.rb
Parent: Object

Methods

create  

Public Class methods

Continuation.create offers a nicer interface for creating continuations than Kernel.callcc.

Example

Count down from 10 to 0 using a continuation.

  continuation, counter = Continuation.create(10)
  puts counter
  continuation.call(counter - 1) if counter > 0

Implement a workalike of Array#inject using continuations. For simplicity’s sake, this is not fully compatible with the real inject.

  class Array
    def cc_inject( value=nil )
      copy = self.clone
      cc, result, item = Continuation.create( value, nil )
      next_item = copy.shift
      if result and item
        cc.call( yield(result, item), next_item )
      elsif next_item
        cc.call( next_item, result )
      end
      result
    end
  end

  [1,2,3,4,5].cc_inject { |acc, n| acc + n }       # -> 15

Explanation

I’ve got no idea how it works. TODO: work it out. In particular, what do the arguments do? And what the hell is going on in cc_inject???!?

See Also

This method is included in the ‘extensions’ package primarily to support Binding.of_caller.

Credits

Continuation.create was written and demonstrated by Florian Gross. See ruby-talk:94681.

[Source]

# File lib/extensions/continuation.rb, line 61
    def Continuation.create(*args, &block)
      cc = nil
      result = callcc { |c|
        cc = c
        block.call(cc) if block and args.empty?
      }
      result ||= args
      return *[cc, *result]
    end

[Validate]