From: Shin-ichiro HARA Date: 2003-03-18T14:21:08+09:00 Subject: Re: Iterator using Continuations Paul wrote: >This looks like a reasonable approach, particularly for an example. I think so too, and add more comments: 1) If the enumerable object has nil, hasNext returns false. It will stop the loop. ex) iter = Iterator.new([1, nil, 5]) while iter.hasNext? #=> stops at nil puts iter.next end 2) The symmetry of @back and @next is ignored. The following is a little improvement of the original code: class Iterator def initialize(enum) @next = nil @back = nil enum.each do |el| @current = el callcc do |cc| @next = cc if @back then @back.call else return end end end @next = nil @back.call if @back end def hasNext? @next end def next last = @current callcc do |cc| @back = cc @next.call if @next end last end end As others said, the library using callcc is not a tool for real applications. But it attracts theoritical interest. I collected the very short codes for Continuation: http://blade.nagaokaut.ac.jp/~sinara/ruby/callcc-lib/ It includes the generic library CoThread. Using this, the iterator can be written as follows: require "co-thread" class Iterator def initialize(enum) @ct = CoThread.new @ct.fork do prev = nil @more = true enum.each do |x| @ct.pass(prev) prev = x end @more = false @ct.pass(prev) end @ct.pass end def hasNext? @more end def next @ct.pass end end Shin-ichiro HARA