【发布时间】:2015-09-22 04:42:10
【问题描述】:
在“点菜数据类型”中,Swierstra 写道,给定 Free(他称之为 Term)和 Zero,您可以实现 Identity monad:
data Term f a = Pure a
| Impure (f (Term f a))
data Zero a
Term Zero 现在是 Identity monad。我明白为什么会这样。问题是我永远不能使用 Term Zero 作为 Monad 因为讨厌的 Functor f => 约束:
instance Functor f => Monad (Term f) where
return x = Pure x
(Pure x) >>= f = f x
(Impure f) >>= t = Impure (fmap (>>=f) t)
如何使Zero 成为 Functor?
instance Functor Zero where
fmap f z = ???
这里似乎有一个技巧:由于Zero 没有构造函数,因此永远无法使用Impure,因此永远不会调用>>= 的Impure 案例。这意味着 fmap 永远不会被调用,所以从某种意义上说这是可以的:
instance Functor Zero where
fmap f z = undefined
问题是,这感觉像是在作弊。我错过了什么? Zero 真的是 Functor 吗?又或许Zero 不是Functor,这是我们在Haskell 中表达Free 的一个缺点?
【问题讨论】:
-
是的,
Zero是从Hask到0的函子,空类别(然后被嵌入回Hask)。
标签: haskell monads free-monad