【问题标题】:How to set initial value for foldLeft When Using EitherT[Future, Failure, Option[B]]使用 EitherT[Future, Failure, Option[B]] 时如何设置 foldLeft 的初始值
【发布时间】:2019-11-24 18:40:31
【问题描述】:

我在执行foldLeft 的以下函数中使用EitherT[Future, Failure, Option[B]]。如何在下面的代码中设置foldLeft的初始值?

    def doWork[A, B](seq: Set[A])(f: A => EitherT[Future, Failure,  Option[B]]): EitherT[Future, Failure, Set[Option[B]]] = 
        seq.foldLeft(????? how to set this initial value here ????) {
          case (acc, nxt) => acc.flatMap(bs => f(nxt).map(b => bs :+ b))
        }

【问题讨论】:

  • 我想你想以Right(Set.empty) 开头?
  • 使用 Right(Set.empty),acc 没有可调用的 flatMap 函数
  • 如果使用 EitherT.right(Future(Set.empty)),则发现:cats.data.EitherT[Future,Failure,Seq[Option[B]]] [error] required: 猫。 data.EitherT[scala.concurrent.Future,Nothing,Seq[Nothing]]
  • 您似乎混合了 EitherTry 单子。您希望 Either 的左侧参数而不是 Failure 的类型是什么?也许Throwable
  • Failure 只是您的自定义类型在某处实现了吗?

标签: scala scalaz scala-cats


【解决方案1】:

试试

EitherT.rightT[Future, Failure](Set.empty[Option[B]])

像这样

def doWork[A, B](seq: Set[A])(f: A => EitherT[Future, Failure,  Option[B]]): EitherT[Future, Failure, Set[Option[B]]] =
  seq.foldLeft(EitherT.rightT[Future, Failure](Set.empty[Option[B]])) {
    case (acc, nxt) => acc.flatMap(bs => f(nxt).map(b => bs + b))
  }

这是波格丹建议的略短版本

EitherT[Future, Failure, Set[Option[B]]](Future.successful(Right(Set())))
EitherT.rightT[Future, Failure](Set.empty[Option[B]])

【讨论】:

  • 哪个包定义了 EitherT.rightT ?我使用importcats.data.EitherT,但没有rightT
  • 是的,这应该是正确的导入:typelevel.org/cats/datatypes/… 您还必须遵循 Bogdan 的建议并更改操作员。
猜你喜欢
  • 1970-01-01
  • 2018-06-29
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
相关资源
最近更新 更多