Simple Lazy Streams

Given lazy evaluation, it’s not hard at all to cobble together lazy streams. Observe; this uses lazy.rb 0.1:

require 'lazy'

def generate( &generator )
  promise { generator.call( generate( &generator ) ) }
end

def fibs
  state = [ 1, 0 ]
  generate do |rest|
    value = state[0] + state[1]
    state[0] = state[1]
    state[1] = value
    [ value, rest ]
  end
end

def iterate( stream )
  while stream
    yield stream[0]
    stream = stream[1]
  end
end

iterate( fibs ) do |n|
  p n
  break if n > 200
end