Monoid 是一个类型类。 字典对 Monoid 的解释是:app
独异点,带有中性元的半群;函数
这应该是范畴论里的东西,反正我目前是看不懂这个什么群。学习
咱们先学习 newtypethis
data 关键字能够建立类型; type 关键字能够给如今类型设置别名; instance 关键字可让类型变成类型类的实例;spa
newtype 关键字是根据现有数据类型建立新类型。 newtype 跟 data 很像,可是速度更快,不过功能更少,只能接受值构造器,值构造器只能有一个参数。code
newtype CharList = CharList { getCharList :: [Char] } deriving (Eq, Show)
ghci> CharList "this will be shown!"
CharList {getCharList = "this will be shown!"}
ghci> CharList "benny" == CharList "benny"
True
ghci> CharList "benny" == CharList "oisters"
False
复制代码
咱们先用 *
和 ++
做比喻ci
1 * 某值
的结果都是某值[] ++ 某列表
的结果都是某列表(3 * 4) * 5
和 3 * (4 * 5)
同样([1,2] ++ [3,4]) ++ [5,6]
和 [1,2] ++ ([3,4] ++ [5,6])
同样再看 Monoid开发
一个 Monoid 的实例由一个知足结合律的二元函数和一个单位元组成。get
在 * 的定义中 1 是单位元,在++ 的定义中[] 是单位元。string
class Monoid m where
mempty :: m
mappend :: m -> m -> m
mconcat :: [m] -> m
mconcat = foldr mappend mempty
复制代码
因此大部分实例只须要定义 mempty 和 mappend 就好了。默认 concat 大部分时候都够用了。
mempty `mappend` x = x
x `mappend` mempty = x
(x `mappend` y) `mappend` z = x `mappend` (y `mappend` z)
-- 并不要求 a `mappend` b = b `mappend` a,这是交换律
复制代码
Haskell 不会强制要求这些定律成立,因此开发者要本身保证。
Data.Monoid 导出了 Product,定义以下
newtype Product a=Product{getProduct::a}
deriving(Eq,Ord,Read,Show,Bounded)
复制代码
他的 Monoid 实例定义以下:
instance Num a=> Monoid ( Product a) where
mempty=Product 1
Product x `mappend` Product y= Product (x * y)
复制代码
使用方法:
ghci> getProduct $ Product 3 `mappend` Product 9
27
ghci> getProduct $ Product 3 `mappend` mempty
3
ghci> getProduct $ Product 3 `mappend` Product 4 `mappend` Product 2
24
ghci> getProduct.mconcat.map Product $ [3,4,2]
24
复制代码
Product 使得 Num 以乘法的形式知足 Monoid 的要求。
Sum 则是用加法:
ghci> getSum $ Sum 2 `mappend` Sum 9
11
ghci> getSum $ mempty `mappend` Sum 3
3
ghci> getSum.mconcat.mapSum $ [1,2,3]
6
复制代码
书中还说了不少其余相似的例子。
不过我更关注的是 monad,因此接直接跳过了。