Skip to content

Instantly share code, notes, and snippets.

@dmsnell
Last active December 27, 2015 11:07
Show Gist options
  • Save dmsnell/6e8b08b1a58fe911f65f to your computer and use it in GitHub Desktop.
Save dmsnell/6e8b08b1a58fe911f65f to your computer and use it in GitHub Desktop.
Learning Haskell: Combine sample means for multiple experimental runs
import Data.Monoid;
x1 = [1..100]
x2 = [2,4..100]
x3 = [3,6..100]
data Summary = Summary {µ::Float, n::Int} deriving (Show)
instance Monoid Summary where
mempty = Summary { µ = 0, n = 0 }
mappend s1 s2 = Summary {
µ = combinedMean s1 s2,
n = (n s1) + (n s2)
}
count :: [Float] -> Int
count xs = length xs
mean :: [Float] -> Float
mean xs =
let s = sum xs
n = fromIntegral $ count xs
in s / n
describe :: [Float] -> Summary
describe xs = Summary { µ = mean xs, n = count xs }
combinedMean :: Summary -> Summary -> Float
combinedMean s1 s2 =
let n1 = fromIntegral $ n s1
n2 = fromIntegral $ n s2
µ1 = µ s1
µ2 = µ s2
in (µ1 * n1 + µ2 * n2) / (n1 + n2)
main :: IO ()
main = do
putStrLn $ " x1 - " ++ (show $ d1)
putStrLn $ " x2 - " ++ (show $ d2)
putStrLn $ " x3 - " ++ (show $ d3)
putStrLn $ " x1 + x2 - " ++ (show $ d1 <> d2)
putStrLn $ "x1 + x2 + x3 - " ++ (show $ mconcat [d1, d2, d3])
where
[d1, d2, d3] = map describe [x1, x2, x3]
@dmsnell
Copy link
Author

dmsnell commented Dec 24, 2015

Output

          x1 - Summary {µ = 50.5, n = 100}
          x2 - Summary {µ = 51.0, n = 50}
          x3 - Summary {µ = 51.0, n = 33}
     x1 + x2 - Summary {µ = 50.666668, n = 150}
x1 + x2 + x3 - Summary {µ = 50.726776, n = 183}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment