-- Arithmetic Mean of a sequence of numbers module Mean where import Data.Monoid -- the naive solution: with speace leak mean :: (Fractional a) => [a] -> a mean xs = sum xs / fromIntegral (length xs) -- -------------------- -- -- the solution with monoids and a single pass over the sequence mean' :: (Fractional a) => [a] -> a mean' xs = (\ (s, l) -> getSum s / fromIntegral (getSum l)) . mconcat . fmap (\ x -> (Sum x, Sum (1::Int)) ) $ xs -- -------------------- -- -- :set +s for statistics -- -- no meaningful timings within ghci -- -- () -> Double: no result caching t1, t1' :: () -> Double t1 () = mean [1.0 .. 1000000.0] t1' () = mean' [1.0 .. 1000000.0] -- --------------------