Project

General

Profile

Bug #6901 ยป promise.rb

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

 
1
RubyVM::InstructionSequence.compile_option = {
2
  :tailcall_optimization => true,
3
  :trace_instruction => false
4
}
5
eval %q{
6
  class Promise
7
    Content = Struct.new(:type, :value)
8

    
9
    attr_accessor :content
10

    
11
    def initialize(type, value)
12
      @content = Content.new(type, value)
13
    end
14

    
15
    def self.lazy(&block)
16
      new(:lazy, block)
17
    end
18

    
19
    def self.eager(value)
20
      new(:eager, value)
21
    end
22

    
23
    def self.delay
24
      lazy {
25
        eager(yield)
26
      }
27
    end
28

    
29
    def force
30
      case content.type
31
      when :eager
32
        content.value
33
      when :lazy
34
        promise = content.value.call
35
        if content.type != :eager
36
          content.type = promise.content.type
37
          content.value = promise.content.value
38
          promise.content = content
39
        end
40
        force
41
      else
42
        raise ScriptError, "should not reach here"
43
      end
44
    end
45
  end
46
}
47
p Promise.delay { 123 }.force