Created
March 19, 2015 16:19
-
-
Save cschneid/f9b341080b264cd59953 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| module Main where | |
| import Data.Monoid | |
| data Average a = Average { sum :: a, count :: a } deriving (Show) | |
| instance (Fractional a) => Monoid (Average a) where | |
| mempty = Average (fromIntegral 0) (fromIntegral 0) | |
| mappend (Average s1 c1) (Average s2 c2) = Average (s1 + s2) (c1 + c2) | |
| average :: (Eq a, Fractional a) => Average a -> a | |
| average (Average sum 0) = error "Divide by zero, bad!" | |
| average (Average sum count) = sum / count | |
| main :: IO () | |
| main = do | |
| let avg = mempty :: Average Float | |
| let avg2 = avg <> (Average 1 1) | |
| let avg3 = avg2 <> (Average 3 1) | |
| print avg3 | |
| print $ average avg3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment