Is difference between foldl and foldr just the direction of looping? I thought there was a difference in what they did, not just in the direction?
Is difference between foldl and foldr just the direction of looping? I thought there
Share
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’s a difference if your function isn’t associative (i.e. it matters which way you bracket expressions) so for example,
foldr (-) 0 [1..10] = -5butfoldl (-) 0 [1..10] = -55.This is because the former is equal to
1-(2-(3-(4-(5-(6-(7-(8-(9-(10 - 0))))))))), whereas the latter is(((((((((0-1)-2)-3)-4)-5)-6)-7)-8)-9)-10.Whereas because
(+)is associative (doesn’t matter what order you add subexpressions),foldr (+) 0 [1..10] = 55andfoldl (+) 0 [1..10] = 55.(++)is another associative operation becausexs ++ (ys ++ zs)gives the same answer as(xs ++ ys) ++ zs(although the first one is faster – don’t usefoldl (++)).Some functions only work one way:
foldr (:) :: [a] -> [a] -> [a]butfoldl (:)is nonsense.Have a look at Cale Gibbard’s diagrams (from the wikipedia article); you can see


fgetting called with genuinely different pairs of data:Another difference is that because it matches the structure of the list,
foldris often more efficient for lazy evaluation, so can be used with an infinite list as long asfis non-strict in its second argument (like(:)or(++)).foldlis only rarely the better choice. If you’re usingfoldlit’s usually worth usingfoldl'because it’s strict and stops you building up a long list of intermediate results. (More on this topic in the answers to this question.)