使用EitherT [Future,Failure,Option [B]]时如何设置foldLeft的初始值

时间:2019-07-16 04:57:19

标签: scala scalaz scala-cats

我在以下执行EitherT[Future, Failure, Option[B]]的函数中使用foldLeft。如何在下面的代码中为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))
        }

1 个答案:

答案 0 :(得分: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))
  }

这是Bogdan建议的简短版本

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