我在以下执行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))
}
答案 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]])