[Haskell] Monoid

class Monoid m where
  mempty :: m
  mappend :: m -> m -> m
  mconcat :: [m] -> m
  mconcat = foldr mapend mempty

其中m是一个具体类型(:k m = *)。

注:
foldr定义为:

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr step zero (x:xs) = step x (foldr step zero xs)
foldr _      zero []        = zero

Monoid Law
(1)mempty `mapend` x = x
(2)x `mappend` mempty = x
(3)(x `mappend` y) `mappend` z = x `mappend` (y `mappend` z)

Examples

(1)[a]是Monoid类型类的实例

instance Monoid [a] where
  mempty = []
  mappend = (++)
ghci> [1, 2, 3] `mappend` [4, 5, 6]
[1, 2, 3, 4, 5, 6]

ghci> (“one ” `mappend` “two ”) `mappend` “three”
“one two three”

其中,:t “one” = [Char]

(2)Any是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)

注:
(1):k Any = *
(2)“instance Monoid Any where”中的Any是类型,“mempty = Any False”和“Any x `mappend` Any y = Any (x || y)”中的Any是值构造器

ghci> getAny $ Any True `mappend` Any False
True

其中getAnyAny类型的字段读取器。

(3)Maybe a是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)
ghci> Nothing `mappend` Just “andy”
Just “andy”

你可能感兴趣的:([Haskell] Monoid)