【发布时间】:2016-07-31 22:27:56
【问题描述】:
在 Haskell 中,我想让一个 Writer monad 成为一个 monoid 的实例:
instance (Monoid a) => Monoid (Writer (Sum Int) a) where
mempty = return mempty
w1 `mappend` w2 = writer((s++t, s'++t'), Sum (m+n)) where
((s,s'), Sum m) = runWriter w1
((t,t'), Sum n) = runWriter w2
因此,直观地说,如果 Writer monad 的“数据”类型是一个幺半群,我希望能够将整个 Writer 事物也视为一个幺半群(由 mempty 和 mappend 实现。
但这不起作用:GHCI 编译器说
Illegal instance declaration for `Monoid (Writer (Sum Int) a)'
(All instance types must be of the form (T t1 ... tn)
where T is not a synonym.
Use -XTypeSynonymInstances if you want to disable this.)
In the instance declaration for `Monoid (Writer (Sum Int) a)'
而且我真的不知道这里什么类型应该是同义词以及我如何才能符合编译器的规则。
【问题讨论】:
-
不遵守规则:按照编译器的建议启用
-XTypeSynonymInstances来放宽规则。-XFlexiblesInstances也可能是必需的。
标签: haskell functional-programming