Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Haskell have an eager version of `foldr`?

The Foldr Foldl Foldl' wiki page describes the differences between foldr and foldl. Both process lists from left-to-right, but foldr accumulates the result from right-to-left whereas foldl does so from left-to-right.

The page goes on to discourage the use of foldl in favor of the eager version foldl', which is more efficient.

Is there a corresponding eager version of foldr, presumably called foldr'? If so, is there a reason that it isn't mentioned on the wiki page?

like image 254
user200783 Avatar asked Mar 17 '20 12:03

user200783


1 Answers

There's no need for foldr', sonce one can always use foldr f with a strict f to achieve the same goal.

We could define it...

foldr' f a xs = foldr f' a xs
  where f' x y = seq x (seq y (f x y))

... but it's simpler to pass a strict f at the call point instead, if needed.

like image 69
chi Avatar answered Sep 25 '22 20:09

chi