Class | Continuation |
In: |
lib/extensions/continuation.rb
|
Parent: | Object |
Continuation.create offers a nicer interface for creating continuations than Kernel.callcc.
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
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???!?
This method is included in the ‘extensions’ package primarily to support Binding.of_caller.
Continuation.create was written and demonstrated by Florian Gross. See ruby-talk:94681.
# 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