score:4

Accepted answer

a verbose scala version of your sumconcurrently,

def sumconcurrently(numbers: list[int]): future[int] = {
  val (v1, v2) = numbers.splitat(numbers.length / 2)
  for {
    sum1 <- future(v1.sum)
    sum2 <- future(v2.sum)
  } yield sum1 + sum2
}

a more concise version

def sumconcurrently2(numbers: list[int]): future[int] = numbers.splitat(numbers.length / 2) match {
  case (l1, l2) => future.sequence(list(future(l1.sum), future(l2.sum))).map(_.sum)
}

and all this is because we have to partition the list. lets say we had to write a function which takes a few lists and returns the sum of their sum's using multiple concurrent computations,

def sumconcurrently3(lists: list[int]*): future[int] =
  future.sequence(lists.map(l => future(l.sum))).map(_.sum)

if the above looks cryptic... then let me de-crypt it,

def sumconcurrently3(lists: list[int]*): future[int] = {
  val listoffuturesofsums = lists.map { l => future(l.sum) }
  val futureoflistofsums = future.sequence(listoffuturesofsums)
  futureoflistofsums.map { l => l.sum }
}

now, whenever you use the result of a future (lets say the future completes at time t1) in a computation, it means that this computation is bound to happen after time t1. you can do it with blocking like this in scala,

val sumfuture = sumconcurrently(list(1, 2, 3, 4))

val sum = await.result(sumfuture, duration.inf)

val anothersum = sum + 100

println("another sum = " + anothersum)

but what is the point of all that, you are blocking the current thread while for the computation on those threads to finish. why not move the whole computation into the future itself.

val sumfuture = sumconcurrently(list(1, 2, 3, 4))

val anothersumfuture = sumfuture.map(s => s + 100)

anothersumfuture.foreach(s => println("another sum = " + s))

now, you are not blocking anywhere and the threads can be used anywhere required.

future implementation and api in scala is designed to enable you to write your program avoiding blocking as far as possible.

score:1

for the task at hand, the following is probably not the tersest option either:

def sumconcurrently(numbers: vector[int]): future[int] = {
  val (v1, v2) = numbers.splitat(numbers.length / 2)
  future(v1.sum).zipwith(future(v2.sum))(_ + _)
}

as i mentioned in my comment there are several issues with your example.


Related Query

More Query from same tag