让我们定义一个Kleisli
on \/
:
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
,我将删除以前的日志记录历史。
最后一个Q
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
. 是不是因为:
- type MyMonad ewa = ErrorT e (Writer w) a 同构于 (Either ea, w)
- type MyMonad ewa = WriterT w (Either e) a 同构于 Either r (a, w)