是否可以为每个 monad 转换器 `t` 编写类型为 `Monad m => t Identity a -> t m a` 的函数?
Is it possible to write a function of the type `Monad m => t Identity a -> t m a` for every monad transformer `t`?
假设我们有以下类型class。
class MonadTrans t => MonadLower t where
lower :: Monad m => t Identity a -> t m a
作为一个简单的例子,我们可以为 MaybeT
实现一个 MonadLower
的实例,如下所示。
instance MonadLower MaybeT where
lower (MaybeT (Identity maybe)) = MaybeT (return maybe)
但是,我不知道如何为 ContT r
实现 MonadLower
的实例。
instance MonadLower (ContT r) where
lower (ContT f) = ContT $ \k -> ???
甚至可以为每个 MonadTrans t
创建一个 MonadLower t
的实例吗?
如果不是,哪些 monad 转换器(ContT r
旁边)不能有 MonadLower
个实例?
编辑: Edward Kmett has defined a similar type class called MonadHoist
.
class MonadHoist t where
hoist :: (Monad m, Monad n) => (forall a. m a -> n a) -> t m a -> t n a
原来是lower = hoist (return . runIdentity)
.
根据Mauro we can't define a MonadHoist
instance for ContT
[1].
What Edward is proposing is to have a class of functorial monad transformers (transformers which are endofunctors in the category Mon(C) of monads over a category C and monad morphisms)
Note that some transformers, like the continuation monad transformer, are not functorial.
假设我们有以下类型class。
class MonadTrans t => MonadLower t where
lower :: Monad m => t Identity a -> t m a
作为一个简单的例子,我们可以为 MaybeT
实现一个 MonadLower
的实例,如下所示。
instance MonadLower MaybeT where
lower (MaybeT (Identity maybe)) = MaybeT (return maybe)
但是,我不知道如何为 ContT r
实现 MonadLower
的实例。
instance MonadLower (ContT r) where
lower (ContT f) = ContT $ \k -> ???
甚至可以为每个 MonadTrans t
创建一个 MonadLower t
的实例吗?
如果不是,哪些 monad 转换器(ContT r
旁边)不能有 MonadLower
个实例?
编辑: Edward Kmett has defined a similar type class called MonadHoist
.
class MonadHoist t where
hoist :: (Monad m, Monad n) => (forall a. m a -> n a) -> t m a -> t n a
原来是lower = hoist (return . runIdentity)
.
根据Mauro we can't define a MonadHoist
instance for ContT
[1].
What Edward is proposing is to have a class of functorial monad transformers (transformers which are endofunctors in the category Mon(C) of monads over a category C and monad morphisms)
Note that some transformers, like the continuation monad transformer, are not functorial.