semi-coroutine の使用例

ついでに、Luaソースコードに付属するテストで、coroutine (semi-coroutine) を使っているもの 2 つを移植してみました。


フィボナッチ数列の生成。

def generate_fib(n)
    SemiCoroutine.new do
        a = b = 1
        n.times do
            SemiCoroutine.yield(a)
            a, b = b, a+b
        end
    end
end

c = generate_fib(10)
while x = c.resume
    p x
end
$ ruby -rsemicoroutine test.rb
1
1
2
3
5
8
13
21
34
55

エラトステネスのふるい。

def gen(n)
    SemiCoroutine.new do
        (2..n).each {|i| SemiCoroutine.yield(i) }
    end
end

def filter(x, c)
    SemiCoroutine.new do
        while n = c.resume
            SemiCoroutine.yield(n) if n % x != 0
        end
    end
end

c = gen(30)
while n = c.resume
    p n
    c = filter(n, c)
end
$ ruby -rsemicoroutine test.rb
2
3
5
7
11
13
17
19
23
29

今日はとてもめもっぽい日記。