Created
April 6, 2015 20:29
-
-
Save asterite/622c68c149c16f1c2c6a to your computer and use it in GitHub Desktop.
This file contains 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
class Object | |
macro enumerated(method) | |
{{method}} | |
def {{method.name}}({{*method.args}}) | |
Enumerator(typeof({{method.name}}({{*method.args.map &.name}}) { |_z| _z })).new do |y| | |
{{method.name}}({{*method.args.map &.name}}) do |value| | |
y << value | |
end | |
end | |
end | |
end | |
end | |
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 | |
class MyClass | |
enumerated def each(z) | |
yield 1 + z | |
yield 2 + z | |
yield 3 + z | |
end | |
end | |
v = MyClass.new.each(10) | |
p v.next | |
p v.next | |
p v.next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment