简体   繁体   中英

Creating parallel executing List combinators

I have function that splits List[B] in half and returns tuple. I need to release combinators for executing them in parallel.

If I do something like fl.map(x => x.map(...)) it is not parallel.

object Parallel {

  implicit class ParList[A](fl: Future[List[A]]) {

    private def split[B](l: List[B]): (List[B], List[B]) = l.splitAt(l.length / 2)

    def paralFilter(f: A => Boolean): Future[List[A]] = ???

    def paralFold(init: A)(f: (A, A) => A): Future[A] = ???
  }

I understand that I must split list elementwise via split[B] and execute combinators with elements in parallel. How can I do it?

To achieve this use method par of scala.collection.Parallelizable :

object Parallel {

  implicit class ParList[A](fl: Future[List[A]]) {

    private def split[B](l: List[B]): (List[B], List[B]) = l.splitAt(l.length / 2)

    def paralFilter(f: A => Boolean)(implicit ec:ExecutionContext): Future[List[A]] = 
      fl.map(_.par.filter(f).toList)

    def paralFold(init: A)(f: (A, A) => A)(implicit ec:ExecutionContext): Future[A] =
      fl.map(_.par.fold(init)(f))
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM