From: Ramakrishnan Muthukrishnan Date: Tue, 23 Dec 2014 17:06:44 +0000 (+0530) Subject: play more with monoids X-Git-Url: https://git.rkrishnan.org/components/%22news.html/frontends/%22file:/status?a=commitdiff_plain;h=981151b9dc55ce9ed50fe7640018fe776a3d81c5;p=yorgey.git play more with monoids --- diff --git a/misc/monoids.hs b/misc/monoids.hs index 848dab9..f15c89f 100644 --- a/misc/monoids.hs +++ b/misc/monoids.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Monoids where import Data.Monoid @@ -46,3 +47,29 @@ treeDepth' = treeFold 0 (\l _ r -> 1 + max l r) flatten' :: Tree a -> [a] flatten' = treeFold [] (\l x r -> l ++ [x] ++ r) +-- monoids +newtype Sum' a = Sum' a + deriving (Eq, Num, Ord, Show) + +getSum :: Sum' a -> a +getSum (Sum' x) = x + +instance Num a => Monoid (Sum' a) where + mempty = 0 + mappend = (+) + +newtype Prod' a = Prod' a + deriving (Eq, Num, Ord, Show) + +getProd :: Prod' a -> a +getProd (Prod' x) = x + +instance Num a => Monoid (Prod' a) where + mempty = 1 + mappend = (*) + +lst :: [Integer] +lst = [1,5,8,23,423,99] + +prod :: Integer +prod = getProd $ mconcat $ map Prod' lst