【问题标题】:Scala: write for-comprehension with ReaderT and OptionScala:用 ReaderT 和 Option 编写理解
【发布时间】:2019-08-27 00:41:09
【问题描述】:

示例如下:

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
}

我想获得类似的语法。

【问题讨论】:

    标签: scala scala-cats for-comprehension reader-monad


    【解决方案1】:

    试试

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

    【讨论】:

    • 你知道,我有一种感觉,我知道该怎么做。我会说,我尝试了这个选项。但看来,我犯了一些错误,因为它不起作用:(
    猜你喜欢
    • 2019-08-17
    • 2016-01-02
    • 2013-02-15
    • 1970-01-01
    • 2019-05-25
    • 2015-10-09
    • 2018-09-17
    • 2023-03-19
    • 2014-04-13
    相关资源
    最近更新 更多