sun*_*ant 2 scala monad-transformers scalaz
这是我之前的一个问题的后续问题:对Scalaz WriterT和For-yield进行排序
以下代码块是一个排序示例Future,Either并Writer使用EitherT和WriterTmonad变换器; 以下问题是关于如何巧妙地改变那堆变形金刚的行为.
import scalaz._, Scalaz._
class Example[F[_], L] (val logFn: (String) => L)(implicit val f: Monad[F], l: Monoid[L])
{
type T = Throwable
type EF[?] = EitherT[F, T, ?]
type WEF[?] = WriterT[EF, L, ?]
private def unreliableInt (i: Int): T Either Int = new java.util.Random ().nextBoolean match {
case false => Right (i)
case true => Left (new Exception (":-("))
}
private def fn (i: Int): WEF[Int] = WriterT.put[EF, L, Int](EitherT.fromEither[F, T, Int](f.point (unreliableInt (i))))(l.zero)
private def log (msg: String): WEF[Unit] = WriterT.put[EF, L, Unit](EitherT.right[F, T, Unit](f.point (())))(logFn (msg))
private def foo (): WEF[Int] = for {
_ <- log ("Start")
x <- fn (18)
_ <- log ("Middle")
y <- fn (42)
_ <- log ("End")
} yield x + y
def bar (): F[(Option[Int], L)] = {
val barWEF: WEF[Int] = foo ()
// Pull out the logs.
val logsEF: EF[L] = barWEF.written
val logsF: F[L] = logsEF.toEither.map {
case Right (x) => x
case Left (e) => logFn(s"Not the logs we are looking for ${e.getMessage}")
}
// Pull out the value.
val resEF: EF[Int] = barWEF.value
val resF: F[Option[Int]] = resEF.run.map {
case \/- (r) => r.some
case -\/ (ex) => None
}
for {
logs <- logsF
response <- resF
} yield (response, logs)
}
}
object Program
{
def main (args : Array[String]) = {
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
type L = List[String]
type F[?] = Future[?]
implicit val l: Monoid[L] = new Monoid[L] { def zero = Nil; def append (f1: L, f2: => L) = f1 ::: f2 }
implicit val f: Monad[F] = scalaz.std.scalaFuture.futureInstance
def createLog (s: String) = s :: Nil
val example = new Example[F, L] (createLog)
val result = Await.result (example.bar (), 5 seconds)
println ("Context logs attached:" + result._2.foldLeft ("") { (a, x) => a + "\n$ " + s"$x"})
println ("Result:" + result._1)
}
}
Run Code Online (Sandbox Code Playgroud)
该功能foo不像我需要的那样; 功能bar和main功能说明了问题.
所需的行为main将始终打印以下结果之一:
Context logs attached:
$ Start
Result:None
Run Code Online (Sandbox Code Playgroud)
要么
Context logs attached:
$ Start
$ Middle
Result:None
Run Code Online (Sandbox Code Playgroud)
要么
Context logs attached:
$ Start
$ Middle
$ End
Result:Some(60)
Run Code Online (Sandbox Code Playgroud)
main但是,该函数不应打印以下内容:
Context logs attached:
$ Not the logs we are looking for :-(
Result:None
Run Code Online (Sandbox Code Playgroud)
但这正是它的作用.当两个fn1和fn2是成功的,foo表现为必需的,main打印出所有的日志.如果其中一个或两个fn1或fn2返回一个Left函数bar返回没有日志,主继续只打印异常.没有办法看到它在日志中有多远.
似乎这个特定的变换器堆栈的行为方式如果-\/序列中有一个,那么日志记录上下文就被简单地映射出来......
看看Scalaz代码WriterT看起来很可能是这样的:
final case class WriterT[F[_], W, A](run: F[(W, A)])
Run Code Online (Sandbox Code Playgroud)
WriterT是一个案例类,其唯一成员是run.关于这个例子run是我们的日志记录context(A)和我们的结果的元组,两者都包含在相同的EitherT(F)中. W并且A按类型绑定数据,以便它们大多数都在左边,或者都在右边.
我可以推测,我需要一个WriterT略有不同的自定义版本,将其数据存储得有点像这样,只允许在一个新的内部访问编写器部分Applicative[F].point:
final case class WriterT[F[_], W, A](wF: F[W], vF:F[A]) {
def run: F[(W, A)] = for {
w <- wF
v <- vF
} yield (w, v)
}
Run Code Online (Sandbox Code Playgroud)
虽然我不确定创建自己的WriterT类型类是否是解决此问题并实现我想要的行为的可行方法.
我有什么选择?
本文:组合monadic效应解释了这个问题.
所以...
type MyMonad e w a = ErrorT e (Writer w) a是同构的 (Either e a, w)
type MyMonad e w a = WriterT w (Either e) a 是同构的 Either r (a, w)
重新排序monad变换器堆栈如下解决了问题:
import scalaz._, Scalaz._
class Example[F[_], L] (val logFn: (String) => L)(implicit val f: Monad[F], l: Monoid[L])
{
type T = Throwable
type WF[?] = WriterT[F, L, ?]
type EWF[?] = EitherT[WF, T, ?]
private def unreliableInt (i: Int): T Either Int = {
new java.util.Random ().nextBoolean match {
case false => Right (i)
case true => Left (new Exception (":-("))
}
}
private def fn (i: Int): EWF[Int] = unreliableInt (i) match {
case Left (left) => EitherT.left [WF, T, Int] (WriterT.put[F, L, T] (f.point (left))(l.zero))
case Right (right) => EitherT.right [WF, T, Int] (WriterT.put[F, L, Int] (f.point (right))(l.zero))
}
private def log (msg: String): EWF[Unit] = { EitherT.right[WF, T, Unit](WriterT.put[F, L, Unit] (f.point (()))(logFn (msg))) }
private def foo (): EWF[Int] = for {
a <- log ("Start")
x <- fn (18)
b <- log ("Middle")
y <- fn (42)
c <- log ("End")
} yield x + y
def bar (): F[(Option[Int], L)] = {
val barEWF: EWF[Int] = foo ()
// Pull out the logs.
val logsF: F[L] = barEWF.run.written
// Pull out the value.
val resF: F[Option[Int]] = barEWF.run.value.map {
case \/- (r) => r.some
case -\/ (ex) => None
}
for {
logs <- logsF
response <- resF
} yield (response, logs)
}
}
object Program
{
def main (args : Array[String]) = {
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
type L = List[String]
type F[?] = Future[?]
implicit val l: Monoid[L] = new Monoid[L] { def zero = Nil; def append (f1: L, f2: => L) = f1 ::: f2 }
implicit val f: Monad[F] = scalaz.std.scalaFuture.futureInstance
def createLog (s: String) = s :: Nil
val example = new Example[F, L] (createLog)
val result = Await.result (example.bar (), 5 seconds)
println ("Context logs attached:" + result._2.foldLeft ("") { (a, x) => a + "\n$ " + s"$x"})
println ("Result:" + result._1)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
680 次 |
| 最近记录: |