Learn You a Haskell talks about foldl'
as an alternative to foldl
because foldl
is prone to stack overflows.
- According to LYAH,
foldl (+) 0 (replicate 1000000 1)
should stack overflow, but it doesn't on my machine. Why not? Even if I increase that number to 10 million it doesn't overflow. It just takes up a lot of memory until my OS X computer becomes unusable and I have to reboot it. - In what cases should I use
foldl
instead offoldl'
? In my experiencefoldl'
"just works" whereasfoldl
can essentially crash my computer (see above). - I don't understand why there is nothing similar for
foldr
. Why can'tfoldr
stack overflow and why is there nofoldr'
?
answersassumptions: 1. Not sure, did you have any optimizations on? 2. Always use foldl'! it's a rule of thumb. 3. foldr is lazy (it can work on infinite lists btw), so IIRC it doesn't even have an accumulator to be strict in the first place (it's not tail recursive). – MasterMastic Feb 12 '15 at 16:10