# Simple Fibonacci program using continuations
# H. Conrad Cunningham
# 27 November 2006

class FibTest

  # Method FibTest.fib returns a two-element array.  The first element of
  # the returned array is the next element of the Fibonacci sequence
  # 0, 1, 1, 2, 3, 5, 8, ...  The second element of the returned array is
  # a continuation that can be called to generate successive elements of 
  # the sequence.

  def FibTest.fib
    i, j = 0, 1
    while true
      callcc {|cc| return [i,cc]}
      # call of the continuation resumes here
      i, j = j, i + j
    end
  end

  def FibTest.run
    n, fib = FibTest.fib()
    puts n
    while n <= 100000
      n, fib = fib.call
      puts n
    end
    fib = nil
    puts "done!"
  end

end
