This module provides efficient and streaming left folds that you can
combine using
Applicative style.
Import this module qualified to avoid clashing with the Prelude:
>>> import qualified Control.Foldl as Foldl
Use
fold to apply a
Fold to a list:
>>> Foldl.fold Foldl.sum [1..100]
5050
Folds are
Applicatives, so you can combine them using
Applicative combinators:
>>> import Control.Applicative
>>> let average = (/) <$> Foldl.sum <*> Foldl.genericLength
… or you can use
do notation if you enable the
ApplicativeDo language extension:
>>> :set -XApplicativeDo
>>> let average = do total <- Foldl.sum; count <- Foldl.genericLength; return (total / count)
… or you can use the fact that the
Fold type implements
Num to do this:
>>> let average = Foldl.sum / Foldl.genericLength
These combined folds will still traverse the list only once, streaming
efficiently over the list in constant space without space leaks:
>>> Foldl.fold average [1..10000000]
5000000.5
>>> Foldl.fold ((,) <$> Foldl.minimum <*> Foldl.maximum) [1..10000000]
(Just 1,Just 10000000)
You might want to try enabling the
-flate-dmd-anal flag when
compiling executables that use this library to further improve
performance.