Coming from Python if I wanted to create an iterative lazy Fibonacci sequence, I could do something like this:
def fib():
a = 1
b = 2
yield a
yield b
while True:
yield a + b
tmp = a
a = b
b = tmp + b
Grabbing next(fib)
will give me the next element in the sequence by simply adding the previous two elements, so if I want to get the first 1000 Fibonacci elements, I can do that quickly:
fib = fib()
for i in range(0,1000):
print(next(fib))
If I try to reproduce that in Ruby with an Enumerator, it quickly chokes, recalculating the entire sequence each time we call fib.next():
def fib()
Enumerator.new do |yielder|
yielder << 1 << 2
fib.lazy.zip(fib.lazy.drop(1)).each do |a,b|
yielder << a + b
end
end
end
I found another SO post on how to fix a recursive fibonacci with memoization in Ruby, but I am curious, are lazy sequences and generators a thing in Ruby?