Project

General

Profile

Bug #6901 ยป promise.rb

shugo (Shugo Maeda), 08/21/2012 05:00 PM

 
RubyVM::InstructionSequence.compile_option = {
:tailcall_optimization => true,
:trace_instruction => false
}
eval %q{
class Promise
Content = Struct.new(:type, :value)

attr_accessor :content

def initialize(type, value)
@content = Content.new(type, value)
end

def self.lazy(&block)
new(:lazy, block)
end

def self.eager(value)
new(:eager, value)
end

def self.delay
lazy {
eager(yield)
}
end

def force
case content.type
when :eager
content.value
when :lazy
promise = content.value.call
if content.type != :eager
content.type = promise.content.type
content.value = promise.content.value
promise.content = content
end
force
else
raise ScriptError, "should not reach here"
end
end
end
}
p Promise.delay { 123 }.force
    (1-1/1)