以下是示例:
trait Service1 { def s1f = Option(10) }
trait Service2 {
type ReaderS1[A] = ReaderT[Option,Service1,A]
def s2f1: ReaderS1[Int] =
ReaderT(s1 =>
for {
r1 <- Option(1)
r2 <- s1.s1f
} yield r1 + r2
)
}
工作正常。我只想用s2f1
方法来重写ReaderT.apply
:
def s2f2:ReaderS1[Int] =
for {
r1 <- 1.pure[ReaderS1]
r2 <- //how to get result of Service1.s1f and compose it here
} yield r1 + r2
这是Reader[...,Int]
的有效示例,但没有ReaderT[Option,...]
的示例:
import cats.data.Reader
trait Service1 { def s1f = 10 }
trait Service2 { def s2f = 20 }
trait Service3 {
def s3f1:Reader[Service1,Int] = Reader(1 + _.s1f)
def s3f2:Reader[Service2,Int] = Reader(2 + _.s2f)
import cats.syntax.applicative._ //for pure
type Env = (Service1, Service2)
type ReaderEnv[A] = Reader[Env,A] //needed to convert Int via pure
def c:ReaderEnv[Int] =
for {
s1 <- Reader((_:Env)._1)
r2 <- s1.s1f.pure[ReaderEnv]
r1 <- s3f2.local((_:Env)._2)
} yield r1 + r2
}
我想获得类似的语法。
答案 0 :(得分:2)
尝试
import cats.syntax.applicative._
import cats.instances.option._
def s2f2: ReaderS1[Int] =
for {
r1 <- 1.pure[ReaderS1]
r2 <- ReaderT((_: Service1).s1f)
} yield r1 + r2