← Back to context

Comment by mrkeen

10 hours ago

* I don't think you meant to compare forcing each element (as opposed to forcing the input or output data structures)

* If you did mean it that way, I doubt Python can avoid forcing each element that goes through its generators. (Without, say, thunking up each element manually or using a generator of generators, etc.)

Here is Haskell using a fold and a map. It does not force the input, the output, or each element:

  main =

    let lazyInput = zip ([1..] :: [Int])
                        (repeat (error "boom"))

        lazyOutput = foldr (:) [] lazyInput

    in print (sum (map fst (take 10_000_000 lazyOutput)))

  > 50000005000000
  > 9 MiB total memory in use
  > real 0m0.062s