Launching the second version in GHCi:
> length [1..1000000] *** Exception: stack overflow
So, to answer your question: Yes, he suffers from this problem, as expected.
However, the GHC is smarter than the average compiler; if you compile with optimization, it will fix the code for you and make it work in a constant space.
More generally, there are ways to force rigor at specific points in the Haskell code, preventing the creation of deeply nested tricks. Common example: foldl vs. foldl' :
len1 = foldl (\x _ -> x + 1) 0 len2 = foldl' (\x _ -> x + 1) 0
Both functions are left folds that do the βsameβ thing, except foldl lazy and foldl' is strict. The result is that len1 dies with a stack overflow in GHCi, and len2 working correctly.
CA McCann
source share