Created
April 6, 2015 19:33
-
-
Save asterite/c299c8f6c65ac4e9e9e1 to your computer and use it in GitHub Desktop.
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
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