Search code examples
scalacollectionsconcurrencyfuturefold

Folding a sequence with a binary operation that returns Future


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 ?


Solution

  • 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?