Scala:具有不同上下文和依赖项的ReaderT组合

时间:2019-04-05 08:35:40

标签: scala monad-transformers scala-cats reader-monad

返回不同的ReaderT的s3f1s3f2函数的示例:

type FailFast[A] = Either[List[String], A]
trait Service1 { def s1f:Option[Int] = Some(10) }
trait Service2 { def s2f:FailFast[Int] = Right(20) }

import cats.instances.option._

def s3f1: ReaderT[Option, Service1, Int] =
  for {
    r1 <- ReaderT((_: Service1).s1f)
  } yield r1 + 1

import cats.syntax.applicative._
import cats.instances.either._

type ReaderService2FF[A] = ReaderT[FailFast, Service2, A]

def s3f2: ReaderService2FF[Int] =
  for {
    r1 <- ReaderT((_: Service2).s2f)
    r2 <- 2.pure[ReaderService2FF]
  } yield r1 + r2

我尝试编写这两个函数,以使读者返回具有不同的F[_]上下文和相关性:ReaderT[Option, Service1, Int]ReaderT[FailFast, Service2, Int]

我必须以某种方式组合F[_]上下文,这意味着将FailFastOption组合在一起。我认为,将其组合到FailFast[Option]是有意义的:

type Env = (Service1, Service2)
type FFOption[A] = FailFast[Option[A]]
type ReaderEnvFF[A] = ReaderT[FFOption, Env, A]

如何组成s3f1和s3f2:

def c: ReaderEnvFF[Int] =
  for {
    r1 <- //s3f1
    r2 <- //s3f2
  } yield r1 + r2

1 个答案:

答案 0 :(得分:0)

由于您尝试在FailFast中编写单子OptionFFOption,因此您应该再使用一个单子变换器,因此FFOption[A]应该是OptionT[FailFast, A]而不是只是FailFast[Option[A]]

import cats.instances.option._
import cats.instances.either._
import cats.syntax.applicative._
import cats.syntax.either._
import cats.syntax.option._

type Env = (Service1, Service2)
type FFOption[A] = OptionT[FailFast, A]
type ReaderEnvFF[A] = ReaderT[FFOption, Env, A]

def c: ReaderEnvFF[Int] =
  for {
    r1 <- ReaderT[FFOption, Env, Int](p => OptionT(Either.right(s3f1.run(p._1))))     
    r2 <- ReaderT[FFOption, Env, Int](p => OptionT(s3f2.run(p._2).map(_.some)))                          
  } yield r1 + r2

可以用localmapF重写:

def c: ReaderEnvFF[Int] =
  for {
    r1 <- s3f1.local[Env](_._1).mapF[FFOption, Int](opt => OptionT(opt.asRight))
    r2 <- s3f2.local[Env](_._2).mapF[FFOption, Int](ff => OptionT(ff.map(_.some)))                      
  } yield r1 + r2