scala - 从 Writer[W, A] 创建 WriterT[F, W, A]

标签 scala monads scalaz monad-transformers

在 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 没有,但您可以使用 WriterTHoist 实例来完成同样的事情:

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/

相关文章:

java - 给定一个 DateTime 对象,如何获取 Joda Time 中的 DateTimeZone?

haskell - 是否可以纯粹执行 `ST`之类的monad(无需 `ST`库)?

haskell - 与 Arrow 和 Applicative 不同,为什么互让让 ArrowApply 和 Monads 等价?

haskell - 从 Continuation monad 中的 IO monad 转义

scala - 从字符串中提取已知键->值对的惯用方法

scala - Option、Either 等上的折叠和 Traversable 上的折叠有什么关系?

Scala、Groovy、Clojure

Scalaz 等价于 forM_

scala - scalaz.Validation loopSuccess和loopFailure如何工作

scala - Scala 中的 "private[syntax]"