haskell - Practical use of `foldl` -
today when working on 1 little script used foldl
instead of foldl'
. got stack overflow
, imported data.list (foldl')
, happy this. , default workflow foldl
. use foldl'
when lazy version falls evaluate.
real world haskell
says should use foldl'
instead of foldl
in cases. foldr foldl foldl' says
usually choice between
foldr
,foldl'
....
however, if combining function lazy in first argument,
foldl
may happily return resultfoldl'
hits exception.
and 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, sorry, it's rather academic, interesting academic example. asking, there example of practical use of foldl
? mean, when can't replace foldl
foldl'
.
p. s. know, it's hard define term practical
, hope understand mean.
p. p. s. understand, why lazy foldl
default in haskell. don't ask move mountain , make strict version default. interested in examples of exclusive usage of foldl
function :)
p. p. p. s. well, interesting usage of foldl
welcome.
here's more practical example using classic naive fibonacci implementation simulate expensive computation:
fib :: int -> int fib 0 = 1 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) f :: int -> int -> int f b = if b < 1000 b else min b
then if had
> -- turn on statistics illustrative purposes > :set +s > foldl f maxbound $ map fib [30, 20, 15] 987 (0.02 secs, 0 bytes) > foldl' f maxbound $ map fib [30, 20, 15] 987 (4.54 secs, 409778880 bytes)
here have drastic difference in runtime performance between lazy , strict versions, lazy version winning out landslide. numbers may vary computer of course, you'll notice difference in execution speed. foldl'
forces each computation occur, while foldl
not. can useful on like
> foldl f maxbound $ map length [repeat 1, repeat 1, replicate 10 1] 10
unlike fib
example, computation technically involves bottom since length $ repeat 1
never finish computation. not having both arguments f
strict (as foldl'
does), have program halts versus 1 never will.
Comments
Post a Comment