Today when I was working on one little script I used foldl
instead of foldl'
. I got stack overflow
, so I imported Data.List (foldl')
and was happy with this. And this is my default workflow with foldl
. Just use foldl'
when lazy version falls to evaluate.
Real World Haskell
says that we should use foldl'
instead of foldl
in most cases. Foldr Foldl Foldl' says that
Usually the choice is between
foldr
andfoldl'
....
However, if the combining function is lazy in its first argument,
foldl
may happily return a result wherefoldl'
hits an exception.
And a given example:
(?) :: Int -> Int -> Int
_ ? 0 = 0
x ? y = x*y
list :: [Int]
list = [2, 3, undefined, 5, 0]
okey = foldl (?) 1 list
boom = foldl' (?) 1 list
Well, I am sorry, but it's rather academic, interesting but academic example. So I am asking, is there any example of practical use of foldl
? I mean, when we can't replace foldl
with foldl'
.
P. S. I know, it's hard to define term practical
, but I hope you will understand what I mean.
P. P. S. I understand, why lazy foldl
is default in haskell. I don't ask anybody to move the mountain and make strict version as default. I am just really interested in examples of exclusive usage of foldl
function :)
P. P. P. S. Well, any interesting usage of foldl
is welcome.
undefined
, you could also usefoldl
to avoid potentially expensive operations. If your folding function exits early on a successful operation, then you can avoid performing expensive computations through laziness. There might be more clear ways to write it (monoids spring to mind), but folds can be nice for compiler optimizations. – bheklilr