gpt4 book ai didi

scala - cats-effect:如何获得隐式的 NonEmptyParallel

转载 作者:行者123 更新时间:2023-12-04 15:50:13 25 4
gpt4 key购买 nike

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

在下面的代码片段中,有 randomMessage 可以正确编译和运行,但调用 randomMessageF 不会编译,因为作用域上没有隐含的 NonEmptyParallel。但是,哪个隐式使用了 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))
}

}

最佳答案

尝试

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

关于scala - cats-effect:如何获得隐式的 NonEmptyParallel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54127567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com