Jun'uary
Jan'uary » 日志 » Implement external iterator by callcc
Implement external iterator by callcc
Jan 发表于 2008-02-20 13:19:24
Said ruby 1.9 will add a new useful feature named external iterator - the kind of iterator you used in Java/Cpp. It's interesting to implement one ourself by using callcc, in 1.8.6.
Note: It's easy to turn this piece of code into a module or make the external iterator available for all kinds of collections, try yourself :0
code:
Note: It's easy to turn this piece of code into a module or make the external iterator available for all kinds of collections, try yourself :0
code:
data = %w/file edit search view tools options language buffers help/
class Array
class Iterator
attr_accessor :cc, :next_cc
attr_accessor :value, :next_value
def next?
@next_value
end
def next
@value = @next_value
callcc do |cc|
@next_cc = cc
@cc.call
end
@value
end
end
def iterator
@iter = Iterator.new
callcc do |cc|
@iter.next_cc = cc
each do |obj|
callcc do |cc2|
@iter.cc = cc2
@iter.next_value = obj
@iter.next_cc.call
end
end
@iter.next_value = nil
@iter.next_cc.call
end
@iter
end
end
iter = data.iterator
puts iter.next while iter.next?
曾经的这一天...
- » 2007年: 每年的春节我都要吃好多烤羊排,我24岁那年,也是的
- » 2006年: 排序实验
相关日志:
收藏:
QQ书签
del.icio.us
订阅:
Google
抓虾
