Search code examples
scalafunctional-programmingscala-cats

Effect abstraction in Cats and parallel execution


I have the next code written using Cats IO that executes multiple actions in parallel (simplified):

import cats.effect._
import cats.implicits._

import scala.concurrent.ExecutionContext.Implicits.global

    class ParallelExecIO {

        def exec: IO[List[String]] = {
            val foo = IO.shift *> IO("foo")
            val bar = IO.shift *> IO("bar")
            List(foo, bar).parSequence
        }
    }

Is it possible to rewrite this code using effect abstraction? What type evidences should be provided?

Sample:

class ParallelExecIO[F[_]: ConcurrentEffect /* ??? */] {

    def exec: F[List[String]] = {
        val foo = Async.shift[F](implicitly) *> "foo".pure[F]
        val bar = Async.shift[F](implicitly) *> "bar".pure[F]
        List(foo, bar).parSequence 
    }
}

[error] value parSequence is not a member of List[F[String]]


Solution

  • With

    scalaVersion := "2.12.5"
    scalacOptions += "-Ypartial-unification"
    libraryDependencies += "org.typelevel" %% "cats-core" % "1.1.0"
    libraryDependencies += "org.typelevel" %% "cats-effect" % "0.10"
    

    the error is

    Error:(23, 22) could not find implicit value for parameter P: cats.Parallel[F,F]
          List(foo, bar).parSequence
    

    So try

    import cats.Parallel
    import cats.effect.{Async, ConcurrentEffect}
    import cats.implicits._
    import scala.concurrent.ExecutionContext.Implicits.global
    import scala.language.higherKinds
    
    class ParallelExecIO[F[_]: ConcurrentEffect, G[_]](implicit ev: Parallel[F, G]) {
    
      def exec: F[List[String]] = {
        val foo = Async.shift[F](implicitly) *> "foo".pure[F]
        val bar = Async.shift[F](implicitly) *> "bar".pure[F]
        List(foo, bar).parSequence
      }
    }
    

    Surely you can introduce type Parallel[F[_]] = cats.Parallel[F, F] and then this can be rewritten as class ParallelExecIO[F[_]: ConcurrentEffect : Parallel] {...