public
Last active

  • Download Gist
lazye.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#!/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 }

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.