作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 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]
。
关于scala - cats-effect:如何获得隐式的 NonEmptyParallel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54127567/
我正在尝试使用 parMapN 函数,但无法编译代码。如果我的类型是 IO 那么没有问题,但是当我在我的函数上使用类型时,我无法让它工作。 在下面的代码片段中,有 randomMessage 可以正确
我是一名优秀的程序员,十分优秀!