Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]]

like image 459
Alexey Sirenko Avatar asked May 08 '18 11:05

Alexey Sirenko


People also ask

What is cat effect?

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.

What is cats in Scala?

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.


1 Answers

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] {...

like image 59
Dmytro Mitin Avatar answered Oct 16 '22 08:10

Dmytro Mitin