From 981151b9dc55ce9ed50fe7640018fe776a3d81c5 Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan Date: Tue, 23 Dec 2014 22:36:44 +0530 Subject: [PATCH] play more with monoids --- misc/monoids.hs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) 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 -- 2.37.2