Created
February 29, 2012 10:11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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