Skip to content

Instantly share code, notes, and snippets.

@asterite
Created April 6, 2015 19:33
Show Gist options
  • Save asterite/c299c8f6c65ac4e9e9e1 to your computer and use it in GitHub Desktop.
Save asterite/c299c8f6c65ac4e9e9e1 to your computer and use it in GitHub Desktop.
require "big_int"
class Enumerator(T)
include Enumerable(T)
struct Yielder(T)
def initialize
@channel = Channel(T).new(20)
end
def <<(value : T)
@channel.send value
end
def receive
@channel.receive
end
end
def initialize(&block : Yielder(T) ->)
@yielder = Yielder(T).new
spawn do
block.call(@yielder)
end
end
def next
@yielder.receive
end
def each
loop do
yield self.next
end
end
end
fib = Enumerator(BigInt).new do |y|
a = b = 1.to_big_i
loop do
y << a
a, b = b, a + b
end
end
100.times do
puts fib.next
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment