R
Rahul Kumar
[Note: parts of this message were removed to make it a legal post.]
Hi,
Most of the `Enumerable` methods can be used for fiber based generators if
`Fiber` is made enumerable.
class Fiber
include Enumerable
def each
loop { yield self.resume }
end
end
def fib_gen
Fiber.new {
a, b = 0, 1
while true
Fiber.yield a
a, b = b, a + b
end
}
end
# Find the fibonacci number greater than 1000
fib_gen.find {|x| x > 1000 }
# take first 10 fibonacci numbers
fib_gen.take 10
# take_while numbers are smaller than 1000
fib_gen.take_while {|x| x < 1000 }
If it could be the default behavior, it would be very useful. Some methods
won't be applicable, particularly for non-terminating generators in their
default incarnation viz. drop_while. It can either be re-written to advance
the generator using Fiber#resume or it can be left upto the user to handle
infinite sequences correctly.
If I understand correctly, writing generators was one of the purposes of
fibers. Why can't fibers be made enumerable by default?
Hi,
Most of the `Enumerable` methods can be used for fiber based generators if
`Fiber` is made enumerable.
class Fiber
include Enumerable
def each
loop { yield self.resume }
end
end
def fib_gen
Fiber.new {
a, b = 0, 1
while true
Fiber.yield a
a, b = b, a + b
end
}
end
# Find the fibonacci number greater than 1000
fib_gen.find {|x| x > 1000 }
# take first 10 fibonacci numbers
fib_gen.take 10
# take_while numbers are smaller than 1000
fib_gen.take_while {|x| x < 1000 }
If it could be the default behavior, it would be very useful. Some methods
won't be applicable, particularly for non-terminating generators in their
default incarnation viz. drop_while. It can either be re-written to advance
the generator using Fiber#resume or it can be left upto the user to handle
infinite sequences correctly.
If I understand correctly, writing generators was one of the purposes of
fibers. Why can't fibers be made enumerable by default?