cats-effect:如何获取隐式NonEmptyParallel

时间:2019-01-10 11:19:44

标签: scala parallel-processing implicit scala-cats cats-effect

我正在尝试使用parMapN函数,但无法编译代码。如果我的类型是IO,那么就没问题,但是当我在函数上使用类型时,就无法使其正常工作。

在下面的代码段中,存在randomMessage可以正确编译并运行,但是由于在范围上没有隐式的NonEmptyParallel,因此对randomMessageF的调用不会编译。但是然后,哪个隐式正在使用randomMessage?传递contextShift也不起作用。


    import cats.NonEmptyParallel
    import cats.effect._
    import cats.syntax.all._
    import fs2._

    import scala.util.Random

    object Test  extends IOApp {

      def randomMessageF[F[_], A, B, C](toA: => F[A],
                                       toB: => F[B],
                                       toC: (A, B) => C)(implicit nep: NonEmptyParallel[F, F]): Stream[F, C] = Stream.eval {
        val funcA   = toA
        val funcB = toB
        (funcA, funcB).parMapN {
          case (a, b) =>
            toC(a, b)
        }
      }

      def randomMessage[A, B, C](toA: => IO[A],
                                 toB: => IO[B],
                                 toC: (A, B) => C): Stream[IO, C] = Stream.eval {
        val funcA   = toA
        val funcB = toB
        (funcA, funcB).parMapN {
          case (a, b) =>
            toC(a, b)
        }
      }

      def run(args: List[String]): IO[ExitCode] =  {
        println(
          randomMessage(
            IO(Random.nextInt(1000).toString),
            IO(Random.nextString(10)),
            (k: String, v: String) => s"$k:$v"
          ).compile.toList.unsafeRunSync().head)


        println(
          randomMessageF[IO, String, String, String](
            IO(Random.nextInt(1000).toString),
            IO(Random.nextString(10)),
            (k, v) => s"$k:$v"
          )(???).compile.toList.unsafeRunSync().head)

        IO(ExitCode(0))
      }

    }

1 个答案:

答案 0 :(得分:2)

尝试

def randomMessageF[M[_], F[_], A, B, C](toA: => M[A],
                                        toB: => M[B],
                                        toC: (A, B) => C)(implicit 
                                        nep: NonEmptyParallel[M, F]): Stream[M, C] = Stream.eval {
  val funcA = toA
  val funcB = toB
  (funcA, funcB).parMapN {
    case (a, b) =>
      toC(a, b)
  }
}

println(
  randomMessageF/*[IO, IO.Par, String, String, String]*/(
    IO(Random.nextInt(1000).toString),
    IO(Random.nextString(10)),
    (k: String, v: String) => s"$k:$v"
  ).compile.toList.unsafeRunSync().head)

randomMessage中,隐式使用的是NonEmptyParallel[IO, IO.Par]

https://github.com/typelevel/cats-effect/blob/master/core/shared/src/main/scala/cats/effect/IO.scala#L834