原です。
前に [ruby-list:13541] iterator <-> cursor で、内部イテレータを外
部イテレータに直す話があったのですが、更にトリッキーなコードを。
-----^ pingpong.rb
def pingpong(x = nil)
$que ||= []
callcc {|$que[1]|
(c = $que.shift) and c.call(x)
}
end
while x = pingpong
p x #=> 1, 2, 3, 4, 5
end
for i in 1..5
pingpong(i)
end
-----$ pingpong.rb
実は今、[ruby-dev:14816] Generator のというの話出ています。
そちらはそちらで進めるとして、こっちはパズルめいていている
のですが、面白いので書き留めておきます。
-----^ ping-pong.rb
class PingPong
def initialize
pingpong
@pong and yield(self)
end
def pingpong(x = nil)
callcc {|cont|
@ping, @pong = cont, @ping
@pong and @pong.call(x)
}
end
end
if __FILE__ == $0
s = PingPong.new { |s|
for i in 1..5
s.pingpong(i + 10)
end
}
t = PingPong.new { |t|
for i in 1..5
t.pingpong(i + 20)
end
}
5.times do
p [s.pingpong, t.pingpong] #=> [11,21], [12,22], [13,23], [14,24], [15,25]
end
end
-----$ ping-pong.rb
# LC 行けない悔しまぎれに。:-)