Skip to content

@mashiro /lazye.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
#!/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
Something went wrong with that request. Please try again.