如何在scalaz中堆叠ReaderT和WriterT变换器?

时间:2017-04-11 05:15:10

标签: scala scalaz

我在scalaz玩monad变形金刚。我试图将Reader顶部的Writer与底层Id monad堆叠在一起。为了组合它们,我使用MonadReaderMonadWriter类型类。

我设法编译并运行以下代码示例没有编写者(即使用Reader monad,即ReaderT[Id.Id, String, A])。向堆栈添加WriterT时,出现编译错误:

Gist.scala:10: could not find implicit value for parameter F: scalaz.MonadReader[Gist.R,String]
   val MR = MonadReader[R, String]
                       ^

如何为变换器堆栈获取MonadReader的实例?我是否必须使用ReaderWriterStateT或是否有其他方式?

完整代码:

import scalaz.{Id, MonadListen, MonadReader, ReaderT, WriterT}

object Gist {
  import scalaz.std.list._
  import scalaz.syntax.monad._

  type P[A] = ReaderT[Id.Id, String, A]
  type R[A] = WriterT[P, List[String], A]

  val MR = MonadReader[R, String]
  val MW = MonadListen[R, List[String]]

  def apply: R[String] = MR.ask >>= { greeting =>
    MW.tell(List(s"greeting $greeting")) >>= { _ =>
      MW.point(s"Hello $greeting")
    }
  }
}

1 个答案:

答案 0 :(得分:5)

我不完全确定Scalaz为什么不为类似的monad变换器提供此实例(或MonadReader实例),但我猜测答案与事实上,WriterTInstanceN已经goes past 11并加入MonadReader只会让事情变得更加混乱。

你可以在Scalaz的GitHub问题中进行挖掘(或者甚至在IRC频道询问你是否有这种事情的胃),但我不确定答案是否重要。

您可以非常直接地从Haskell mtl移植实例:

instance (Monoid w, MonadReader r m) => MonadReader r (Strict.WriterT w m) where
    ask   = lift ask
    local = Strict.mapWriterT . local
    reader = lift . reader

翻译成Scala的内容如下:

import scalaz.{ MonadReader, MonadTrans, Monoid, WriterT }
import scalaz.syntax.monad._

implicit def monadReaderForWriterT[F[_], I, W](implicit
  F: MonadReader[F, I],
  W: Monoid[W]
): MonadReader[WriterT[F, W, ?], I] = new MonadReader[WriterT[F, W, ?], I] {
  def ask: WriterT[F, W, I] = MonadTrans[WriterT[?[_], W, ?]].liftM(F.ask)

  def local[A](f: I => I)(fa: WriterT[F, W, A]): WriterT[F, W, A] =
    fa.mapT(F.local(f))

  def point[A](a: => A): WriterT[F, W, A] = a.point[WriterT[F, W, ?]]
  def bind[A, B](fa: WriterT[F, W, A])(
    f: A => WriterT[F, W, B]
  ): WriterT[F, W, B] = fa.flatMap(f)
}

请注意,我使用的是kind-projector,因为lambda版本的类型将比Haskell版本长四倍或五倍,而不是仅仅三倍。

一旦您定义了此实例,您就可以编写以下内容:

import scalaz.{ Id, MonadListen, ReaderT }
import scalaz.std.list._

type P[A] = ReaderT[Id.Id, String, A]
type R[A] = WriterT[P, List[String], A]

val MR = MonadReader[R, String]
val MW = MonadListen[R, List[String]]

def apply: R[String] = MR.ask >>= { greeting =>
  MW.tell(List(s"greeting $greeting")) >>= { _ =>
    MW.point(s"Hello $greeting")
  }
}