Scala:使用 ReaderT 和 Option 为理解而写

Scala: write for-comprehension with ReaderT and Option

示例如下:

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
    )
}

它工作正常。我只想在没有 ReaderT.apply 方法的情况下重写 s2f1

  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
}

我想获得类似的语法。

尝试

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

def s2f2: ReaderS1[Int] =
  for {
    r1 <- 1.pure[ReaderS1]
    r2 <- ReaderT((_: Service1).s1f)
  } yield r1 + r2