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?
我不确定为什么删除了其他答案-但是使用普通的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)
我想念什么吗?
尝试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)
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |