Scalaz - 函数组合 - WriterT

3
让我们在“\/”上定义一个Kleisli:
abstract class MyError
case class NumericalError(msg: String) extends MyError

// Either is a Monad with two type parameters: M[A,B] which represent left and right respectively
// Let's create an ad-hoc type
type EEither[+T] = \/[MyError, T]

还有一个用于测试目的的特别函数:

def safeSqrtEither(t: Double): EEither[Double] =
  safeSqrtOpt(t) match {
    case Some(r) => r.right
    case None => NumericalError("Sqrt on double is not define if _ < 0").left
  }
val kSafeSqrtEither = Kleisli.kleisli( (x: Double) => safeSqrtEither(x) )

函数组合可以很顺畅地工作:

val pipeEither = kSafeSqrtEither >>> kSafeSqrtEither
val r5b = pipeEither2 run 16.0
//which gives r5b: EEither[Double] = \/-(2.0)

我想添加日志记录:

type LoggedROCFun[I,O] = I => WriterT[EEither,scalaz.NonEmptyList[String],O]
val sqrtWithLog: LoggedROCFun[Double, Double] =
  (t: Double) =>
    WriterT.put(kSafeSqrtEither(t))(s"squared $t".wrapNel)

这似乎具有所需的行为:

val resA = sqrtWithLog(16.0)
// resA: scalaz.WriterT[EEither,scalaz.NonEmptyList[String],Double] = WriterT(\/-((NonEmpty[squared 16.0],4.0)))

简洁明了。然而,我正在努力编写一个操作器来:

  • WriterT 中的值应用 >>> 进行合并
  • 连接(附加)每个日志,追踪每一步所做的记录

期望输出:

val combinedFunction = sqrtWithLog >>> sqrtWithLog
val r = combinedFunction run 16.0
// r: WriterT(\/-((NonEmpty[squared 16.0, squared 4.0],2.0)))

我的最佳尝试:

def myCompositionOp[I,A,B](f1: LoggedROCFun[I,A])(f2: LoggedROCFun[A,B]): LoggedROCFun[I,B] =
  (x: I) => {
    val e = f1.apply(x)
    val v1: EEither[A] = e.value
    v1 match {
        case Right(v)  => f2(v)
        case Left(err) =>
          val lastLog = e.written
          val v2 = err.left[B]
          WriterT.put(v2)(lastLog)

      }
  }

在上述过程中,我首先将f1应用于x,然后将结果传递给f2。否则,我会直接跳转到Left。这是错误的,因为在Right的情况下,我会丢弃之前的日志记录。
最后一个问题。
val safeDivWithLog: Kleisli[W, (Double,Double), Double] =
  Kleisli.kleisli[W, (Double, Double), Double]( (t: (Double, Double)) => {
    val (n,d) = t
    WriterT.put(safeDivEither(t))(s"divided $n by $d".wrapNel)
  }
  )
val combinedFunction2 = safeDivWithLog >>> sqrtWithLog
val rAgain = combinedFunction2 run (-10.0,2.0)
// rAgain: W[Double] = WriterT(-\/(NumericalError(Sqrt on double is not define if _ < 0)))

不确定为什么在管道切换到 Left 后,日志为何没有传递。是因为:
  • 类型 MyMonad e w a = ErrorT e (Writer w) a 等同于 (Either e a, w)
  • 类型 MyMonad e w a = WriterT w (Either e) a 等同于 Either r (a, w)
因此,我已经更改了顺序
来源: 这里scalaz这里real world haskell on transformers
1个回答

3

您很接近解决问题了——问题只是您已经将Kleisli深埋在内部,而您想要它在外部。您的LoggedROCFun只是一个普通函数,而普通函数的Compose实例要求第一个函数的输出类型与第二个函数的输入类型相匹配。如果您将sqrtWithLog变成Kleisli箭头,它就可以正常工作:

import scalaz._, Scalaz._

abstract class MyError
case class NumericalError(msg: String) extends MyError

type EEither[T] = \/[MyError, T]

def safeSqrtEither(t: Double): EEither[Double] =
  if (t >= 0) math.sqrt(t).right else NumericalError(
    "Sqrt on double is not define if _ < 0"
  ).left

type W[A] = WriterT[EEither, NonEmptyList[String], A]

val sqrtWithLog: Kleisli[W, Double, Double] =
  Kleisli.kleisli[W, Double, Double](t =>
    WriterT.put(safeSqrtEither(t))(s"squared $t".wrapNel)
  )

val combinedFunction = sqrtWithLog >>> sqrtWithLog
val r = combinedFunction run 16.0

请注意,为了使代码成为一个完整的工作示例,我稍微修改了您的代码。
针对您的评论,如果您想让编写者在失败时累加,您需要在转换器中翻转EitherWriter的顺序。
import scalaz._, Scalaz._

abstract class MyError
case class NumericalError(msg: String) extends MyError

type EEither[T] = \/[MyError, T]

def safeSqrtEither(t: Double): EEither[Double] =
  if (t >= 0) math.sqrt(t).right else NumericalError(
    "Sqrt on double is not define if _ < 0"
  ).left

type W[A] = Writer[List[String], A]
type E[A] = EitherT[W, MyError, A]

val sqrtWithLog: Kleisli[E, Double, Double] =
  Kleisli.kleisli[E, Double, Double](t =>
    EitherT[W, MyError, Double](safeSqrtEither(t).set(List(s"squared $t")))
  )

val constNegative1: Kleisli[E, Double, Double] =
  Kleisli.kleisli[E, Double, Double](_ => -1.0.point[E])

val combinedFunction = sqrtWithLog >>> constNegative1 >>> sqrtWithLog

然后:
scala> combinedFunction.run(16.0).run.written
res9: scalaz.Id.Id[List[String]] = List(squared 16.0, squared -1.0)

请注意,在 writer 中,这不适用于 NonEmptyList,因为您需要在例如 constNegative1.run(0.0).run.written 的情况下能够返回一个空日志。我使用了 List,但在实际代码中,您可能希望使用一种更便宜的追加类型。

感谢您的帮助。看起来当出现Left时,WriterT会丢弃日志(请参见上文)。谢谢。 - NoIdeaHowToFixThis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接