by lalaithion · 1y ago · 0 comments
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.
Your code didn't show a quadratic blowup in the timing:
main = print . sum $ take 1000000 ints
ints = 1 : map (+1) ints
500000500000
real 0m0.022s
user 0m0.021s
sys 0m0.000s