使用返回Future的二进制操作折叠序列

Mic*_*ael 5 collections concurrency scala future fold

假设我有一个函数op: (Int, Int) => Future[Int],需要编写一个新函数foo

def foo(xs: Seq[Int], 
        zero: Int, 
        op: (Int, Int) => Future[Int]): Future[Int] = ???
Run Code Online (Sandbox Code Playgroud)

foo应该作为foldLeft并按op顺序应用于中的所有元素xs,例如:

val op: (Int, Int) => Future[Int] = (x, y) => Future(x + y)
val xs = (1 to 10)
val fut = foo(xs, 0, op) // should return Future of 55
fut.value // Some(Success(55))
Run Code Online (Sandbox Code Playgroud)

您将如何实施foo

pme*_*pme 6

我不确定为什么删除了其他答案-但是使用普通的Scala可以为我工作:

 def foo(xs: Seq[Int], zero: Int, op: (Int, Int) => Future[Int]): Future[Int] =  

    xs.foldLeft(Future.successful(zero))((a, b) => a.flatMap(op(_, b)))
Run Code Online (Sandbox Code Playgroud)

我想念什么吗?


Mar*_*lic 5

尝试foldM从猫:

import cats._
import cats.implicits._

def foo(xs: Seq[Int], zero: Int, op: (Int, Int) => Future[Int]): Future[Int] =
  Foldable[List].foldM(xs.toList, zero)(op)
Run Code Online (Sandbox Code Playgroud)