对于
Writer
Monoid
.
tell
使用
mappend
将其参数添加到运行日志。
然而,对于整数,对于
幺半群
例子其中之一是加法,单位元素为0:
instance Monoid Int where
mempty = 0
mappend = (+)
另一个是与1:
instance Monoid Int where
mempty = 1
mappend = (*)
Haskell设计师应该如何在这两个选项之间进行选择?它们都同样有效,在不同的情况下都很有用。最后,他们决定不发表意见,离开了
Int
没有
幺半群
实例,而不是提供两个
newtype
s允许您选择所需的实例。
newtype Sum n = Sum { getSum :: n }
instance Num n => Monoid (Sum n) where
mempty = Sum 0
Sum x `mappend` Sum y = Sum (x + y)
newtype Product n = Product { getProduct :: n }
instance Num n => Monoid (Product n) where
mempty = Product 1
Product x `mappend` Product y = Product (x * y)
这两个
新类型
in the
Data.Monoid
module
作家
monad,所以您需要做的就是将所有类型签名从
Writer Integer
到
Writer (Sum Integer)
.
另一种类型的错误是GHC,它告诉您不能编写
作家
行动
State
行动你有
wcm :: State (Integer, Bool) String
和
ccm :: Writer Integer String
Integer
您的状态的组件来添加内容(我猜这意味着与
作家
单子转换器
版本
状态
:
wcm :: StateT Bool (Writer Integer) String
然后使用
lift
带着朴素的老人
写入整数
单子进入
StateT
-这丰富了上下文。
如果您还不习惯monad transformers,另一种选择是在
State (Integer, Bool)
单子。