【问题标题】:Is it possible to write a function of the type `Monad m => t Identity a -> t m a` for every monad transformer `t`?是否可以为每个 monad 转换器 `t` 编写类型为 `Monad m => t Identity a -> t m a` 的函数?
【发布时间】:2019-12-07 09:26:39
【问题描述】:

假设我们有以下类型类。

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 定义了一个类似的类型类,称为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)

【问题讨论】:

  • lower 只是 fmap (pure . runIdentity) 吗?我在这里错过了什么?
  • @amalloy ContT r Identity a(a -> Identity r) -> Identity r。因此,fmap 不起作用。
  • @amalloy 原来lowerhoist (pure . runIdentity),其中hoistEdward Kmett在他的MonadHoist类中定义的一个函数。

标签: haskell monads monad-transformers


【解决方案1】:

根据Mauro,我们不能为ContT定义MonadHoist实例[1]

Edward 的提议是拥有一类 functorial monad 转换器(转换器是 Mon(C) 类别中的 endofunctor,在类别 C 和 monad 态射上)

请注意,有些转换器,例如 continuation monad 转换器,不是函数式的。

【讨论】:

    猜你喜欢
    • 2012-04-07
    • 2022-10-13
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多