Last active
June 3, 2016 06:40
-
-
Save tippenein/7532333fe9ee82d94618803b2d2655b0 to your computer and use it in GitHub Desktop.
commutative monoid (https://www.youtube.com/watch?v=cMY1KVrJk0w&feature=youtu.be&t=1m51s)
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 Control.Parallel | |
import Data.Monoid | |
data Collection = Collection | |
{ s :: Integer | |
, average :: Double | |
, count :: Integer | |
} | |
deriving (Show) | |
instance Monoid Collection where | |
mempty = Collection 0 0 0 | |
(Collection x1 y1 count1) `mappend` (Collection x2 y2 count2) = | |
Collection (x1 + x2) avg newCount | |
where | |
avg = realToFrac (x1 + x2) / (fromIntegral newCount) | |
newCount = count1 + count2 | |
mconcat = foldr mappend mempty | |
c1 = Collection 1 1 1 | |
c2 = Collection 10 10 1 | |
c3 = Collection 4 4 1 | |
group1 = replicate 901000 c1 | |
group2 = replicate 991900 c2 | |
group3 = replicate 1391000 c3 | |
mainPar = | |
a `par` b `par` c `pseq` mconcat [a,b,c] | |
where | |
a = mconcat group1 | |
b = mconcat group2 | |
c = mconcat group3 | |
mainNormal = | |
mconcat group1 <> mconcat group2 <> mconcat group3 | |
main = print mainPar | |
-- ghc -threaded -rtsopts --make monoidal_sum | |
-- ./monoidal_sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment