在 Scalaz 中,是否有一种简单的方法来转换 Writer[W, A]
的实例(这是 WriterT[Id, W, A] 的别名)
到 WriterT[F, W, A]
?
我正在寻找类似于 optionT
函数与 point
结合的东西,但适合作家:
例如
// Similar situation, but using OptionT
val opt: Option[String] = Some("log")
val optT: OptionT[IO, String] = optionT(opt.point[IO])
// Case in hand, using WriterT
val w: Writer[String, Unit] = "log".tell
val wt: WriterT[IO, String, Unit] = ???
// Similar scenario
val w: Writer[String, Int] = 3.set("log")
val wt: WriterT[IO, String, Int] = ???
最佳答案
一些一元类型具有有助于此类操作的lift
方法:
import scalaz._, Scalaz._, effect.IO
val stateIO: StateT[IO, Int, Unit] = put(10).lift[IO]
Writer
没有,但您可以使用 WriterT
的 Hoist
实例来完成同样的事情:
type StringWriter[F[_], A] = WriterT[F, String, A]
def fromId[F[_]: Applicative]: Id ~> F = new (Id ~> F) {
def apply[A](a: A) = a.point[F]
}
val w: Writer[String, Unit] = "log".tell
val wt: WriterT[IO, String, Unit] = Hoist[StringWriter].hoist(fromId[IO]).apply(w)
这不是很方便,但在使用 monad 转换器时你必须习惯这一点。
关于scala - 从 Writer[W, A] 创建 WriterT[F, W, A],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35362240/