Skip to content

Instantly share code, notes, and snippets.

@jjclxrk
Last active June 10, 2020 03:07
Show Gist options
  • Select an option

  • Save jjclxrk/c4b9ab2969fe7a5a5f62c5683de1a128 to your computer and use it in GitHub Desktop.

Select an option

Save jjclxrk/c4b9ab2969fe7a5a5f62c5683de1a128 to your computer and use it in GitHub Desktop.
import Data.List (foldl')
import Data.Time
import Data.Time.Clock.System
main = do
bench "stats6" stats6 [1..10000000]
bench "stats5" stats5 [1..10000000]
bench "stats4" stats4 [1..10000000]
bench :: (Show b) => String -> ([a] -> b) -> [a] -> IO ()
bench name f xs = do
t0 <- getSystemTime
putStrLn name >> print (f xs)
t1 <- getSystemTime
print $ diffUTCTime (systemToUTCTime t1) (systemToUTCTime t0)
-- three passes
stats4 :: (Num a) => [a] -> (Int, a, a)
stats4 xs = (length xs, sum xs, sum . map (\x -> x * x) $ xs)
-- one pass, strict left fold
stats5 :: (Num a) => [a] -> (Int, a, a)
stats5 = foldl' (\(l,s,sq) x -> (l+1, s+x, sq+x*x)) (0,0,0)
-- one pass, lazy right fold
stats6 :: (Num a) => [a] -> (Int, a, a)
stats6 = foldr (\x (l,s,sq) -> (l+1, s+x, sq+x*x)) (0,0,0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment