Haskell port using Control.Parallel with Scala

The Haskell code below uses par and pseq to execute multiple multi-chip numbers as a toy to show several cores used. What would be the easiest and most idiomatic way to express this in Scala? Futures and Promises seem promising (um), and I looked at scalaz.concurrent , for example. this example , but I can not find the documents to explain all this.

 import Control.Parallel main = a `par` b `par` c `pseq` print (a + b + c) where a = ack 3 10 b = fac 42 c = fib 35 fac 0 = 1 fac n = n * fac (n-1) ack 0 n = n+1 ack m 0 = ack (m-1) 1 ack mn = ack (m-1) (ack m (n-1)) fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) 
+4
source share
2 answers

You can translate your example into Scala like this:

 import concurrent.{Await, Future, future} import concurrent.ExecutionContext.Implicits.global import concurrent.duration.Duration object Main extends App { val fac: Int => Int = { case 0 => 1 case n => n * fac(n-1) } val ack: (Int, Int) => Int = { case (0, n) => n + 1 case (m, 0) => ack (m-1, 1) case (m, n) => ack (m-1, ack(m, n-1)) } val fib: Int => Int = { case 0 => 0 case 1 => 1 case n => fib(n-1) + fib(n-2) } val fa = future { ack(3, 10) } val fb = future { fac(42) } val fc = future { fib(35) } val x = for (((a, b), c) <- fa zip fb zip fc) yield (a + b + c) val result = Await.result(x, Duration.Inf) //awaiting synchronously after the result println(s"Value is: $result") } 

The future { fib(3, 10) } bit will create an asynchronous calculation that will be executed in another thread of execution and will return a Future object. You can then put all your futures into one big future that will provide a list of all the results using Future.sequence .

We can map the result of this last future into the sum of the results, thereby obtaining the final value.

In this ultimate future, we can do several things. We can put it together or attach callbacks to it, or we can wait synchronously for a certain period of time. In my example, I wait synchronously after the result for an infinite period of time.

+4
source

I suggest you use futures because they are part of the standard library since 2.10 and are very easy to use. I will not port your code, but I give you an example for you to understand.

 // not tailrec, will Qaru for larger numbers def fib(x: Int): Int = x match { case 0 | 1 => x case x => fib(x-1) + fib(x-2) } import scala.concurrent._ import ExecutionContext.Implicits.global // create all the futures val futures = Seq(future(fib(3)), future(fib(4)), future(fib(5))) // make a Future[Seq[Int]] out of Seq[Future[Int]] and sum the ints val sumFuture = Future.sequence(futures).map(_.sum) // if the future is completed successfully print the result sumFuture.onSuccess { case x => println(x) } 
+1
source

All Articles