/combineSummaryStats.hs Secret
Last active
December 27, 2015 11:07
Star
You must be signed in to star a gist
Learning Haskell: Combine sample means for multiple experimental runs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output