19. ListはMonoid
x `mappend` y = y `mappend` x
は満たさなくて良い
instance Monoid [a] where
mempty = []
mappend = (++)
Monoid [] ではないことに注意
20. 数をMonoidに
instance Num a => Monoid a where
mempty = 1
mappend = (*)
instance Num a => Monoid a where
mempty = 0
mappend = (+)
でも、こっちも定義したい
いったいどうしたら…
21. そこで newtype
newtype Product a =
Product { getProduct :: a }
deriving (Eq,Ord,Read,Show,Bounded)
instance Num a => Monoid (Product a) where
mempty = Product 1
Product x `mappend` Product y =
Product (x * y)
> getProduct $ Product 3 `mappend` Product 9
27
Sum も同じように定義されている
22. AnyとAll
•Boolに対するMonoid
newtype Any =
Any { getAny :: Bool }
deriving (Eq,Ord,Read,Show,Bounded)
instance Monoid Any where
mempty = Any False
Any x `mappend` Any y =
Any (x || y)
25. Maybe monoid
instance Monoid a => Monoid (Maybe a) where
mempty = Nothing
Nothing `mappend` m = m
m `mappend` Nothing = m
Just m1 `mappend` Just m2 =
Just (m1 `mappend` m2)
中身が Monoid の場合はこんな定義ができる
26. Maybe monoid
First
newtype First a = First {getFirst :: Maybe a}
deriving (Eq,Ord,Read,Show)
instance Monoid (First a) where
mempty = First Nothing
First (Just x) `mappend` _ = First (Just x)
First Nothing `mappend` x = x
> getFirst . mconcat . map First $
[Nothing, Just 9, Just 10]
Just 9
同様に Last a も定義されている