Suppose I've got a function op: (Int, Int) => Future[Int]
and need to write a new function foo
:
def foo(xs: Seq[Int],
zero: Int,
op: (Int, Int) => Future[Int]): Future[Int] = ???
foo
should work as foldLeft
and apply op
sequentially to all elements in xs
, e.g.:
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))
How would you implement foo
?
I'm not sure why the other answer was deleted - but with plain Scala this works for me:
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)))
Do I miss something?
Try foldM
from cats:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With