by louthy · 1y ago · 0 comments
def ints():
yield 1
yield from map(lambda x: x + 1, ints())
Surely it would always yield a stream of `1`s? Seems very weird to my brain. "As simple as that" it is not!For the second item, we grab the first item from ints(), and then apply the map operation, and 1+1 is 2.
For the third item, we grab the second item from ints(), and then apply the map operation, and 1+2 is 3.
The extra cost is not in the recursive calls, of which there is only one per returned number. The cost is in achieving a yielded value n by starting with 1 and adding 1 to it (n-1) times. The given Haskell code:
ints = 1 : map (+1) ints
has the exact same problem, and it's just as quadratic. It might have a somewhat better constant factor, though (even apart from Python being interpreted) because there's less function calls involved.