首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >cats-effect:如何获得隐式NonEmptyParallel

cats-effect:如何获得隐式NonEmptyParallel
EN

Stack Overflow用户
提问于 2019-01-10 19:19:44
回答 1查看 321关注 0票数 3

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

在下面的代码片段中,有可以正确编译和运行的randomMessage,但调用randomMessageF不会编译,因为作用域上没有隐含的NonEmptyParallel。但是,哪个隐式使用的是randomMessage呢?传递contextShift也不起作用。

代码语言:javascript
复制
    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))
      }

    }
EN

回答 1

Stack Overflow用户

发布于 2019-01-10 22:21:26

试一试

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54127567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档