Learning Haskell, I came across the fact that foldl creates thunks and might crash the stack, so it’s better to use foldl' from Data.List. Why is it just foldl, and not, for example, foldr?
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is no need for
foldr'because you can cause the effect yourself.Here is why: Consider
foldl f 0 [1,2,3]. This expands tof (f (f 0 1) 2) 3, so by the time you get anything back to work with, thunks for(f 0 1)and(f (f 0 1) 2)have to be created. If you want to avoid this (by evaluating these subexpressions before continuing), you have to instructfoldlto do it for you – that isfoldl'.With
foldr, things are different. What you get back fromfoldr f 0 [1, 2, 3]isf 1 (foldr f 0 [2, 3])(where the expression in parenthesis is a thunk). If you want to evaluate (parts of) the outer application off, you can do that now, without a linear number of thunks being created first.But in general, you are using
foldrwith lazy functions forfthat can already do something (e.g. produce list constructors) before looking at the second argument.Using
foldrwith a strictf(e.g.(+)) has the unwanted effect of putting all applications on the stack until the end of the list is reached; clearly not what you want, and not a situation where a however-lookingfoldr'could help.