Skip to content

Instantly share code, notes, and snippets.

@mashiro
Created February 29, 2012 10:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mashiro/1939610 to your computer and use it in GitHub Desktop.
Save mashiro/1939610 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'fiber'
module Lazy
module Enumerable
def lazy(method = :each)
Lazy::Enumerator.new do
if block_given?
Fiber.yield yield while true
else
e = ::Enumerator.new self, method
Fiber.yield e.next while true
end
end
end
end
class Enumerator
include Lazy::Enumerable
def initialize
@context = Fiber.new do
yield if block_given?
end
end
def next
@context.resume
end
def to_a
::Enumerator.new(self).map { |it| it }
end
def each
if block_given?
loop { yield self.next }
else
self
end
end
def map
lazy do
it = self.next
block_given? ? yield(it) : it
end
end
end
end
Array.send :include, Lazy::Enumerable
e = (0...10).to_a.lazy
e = e.map { |x| x + 1 }
e = e.map { |x| x * 2 }
e.each { |x| puts x }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment