4 ms·
let nums = take 10000000 naturals print $ (sum nums, length nums) > Because the nums list is used for both sum and length computations, the compiler can’t
by Joker_vD 4y ago
let nums = take 10000000 naturals
print $ (sum nums, length nums)
> Because the nums list is used for both sum and length computations, the compiler can’t discard list elements until it evaluates both.
Now that makes me wonder, if I write something like
print $ (sum (take 10000000 naturals), length (take 10000000 naturals))
will it run in constant memory? I think it ought to, but are there mechanisms in GHC optimizer to prevent extraction of CSEs that would cause huge increases in memory consumption?
- endgame 4y agoThe solution to this is a package like https://hackage.haskell.org/package/foldl https://hackage.haskell.org/package/foldl , which lets you fuse multiple traversals of a lazy list into a single pass and get the laziness right.
- hgsgm 4y agoIt's both solvable and easy to accidentally have blowups by accident.
- sbergot 4y agoyeah sadly this summarize my haskell experience. I would hate to do code reviews in haskell.