Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 719
Michael Avatar asked Jun 19 '19 09:06

Michael


2 Answers

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?

like image 118
pme Avatar answered Dec 20 '22 12:12

pme


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)
like image 35
Mario Galic Avatar answered Dec 20 '22 14:12

Mario Galic