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]]
Cats EffectThe pure asynchronous runtime for Scala Cats Effect is a high-performance, asynchronous, composable framework for building real-world applications in a purely functional style within the Typelevel ecosystem.
Cats is a library which provides abstractions for functional programming in the Scala programming language. Scala supports both object-oriented and functional programming, and this is reflected in the hybrid approach of the standard library.
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] {...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With