The foldl
function comes with a strict analog foldl'
. Is there a reason why scanl
doesn't need a scanl'
alternative or did they simply not include it in the standard library?
There's no need for it. The strictness of foldl'
allows it to eliminate thunks immediately as it traverses its input list.
foldl' (+) 0 [1,2,3] foldl (+) 0 [1,2,3]
foldl' (+) 1 [2,3] foldl (+) (0 + 1) [2,3]
foldl' (+) 3 [3] foldl (+) ((0 + 1) + 2) [3]
foldl' (+) 6 [] foldl (+) (((0 + 1) + 2) + 3) []
6 (((0 + 1) + 2) + 3)
((1 + 2) + 3)
(3 + 3)
6
But when you do scanl
it produces a list containing each one of those steps
scanl (+) 0 [1,2,3]
[ 0
, 0 + 1
, (0 + 1) + 2
, ((0 + 1) + 2) + 3
]
And you must traverse the entire list to see the final result which lets you control how the thunks are forced. This pushes the control of evaluation to the consumer of the list.
Well, I'm not sure if scanl'
isn't needed, but it probably is a much rarer need than foldl'
, since you typically consume the result of scanl
element by element, and hence force it as you go exactly the way foldl'
does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With