gpt4 book ai didi

scala - Cats 中的效果抽象和并行执行

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

我有使用 Cats IO 编写的下一个代码,它并行执行多个操作(简化):

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

是否可以使用效果抽象重写此代码?应该提供什么类型的证据?

样本:
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]]

最佳答案


scalaVersion := "2.12.5"
scalacOptions += "-Ypartial-unification"
libraryDependencies += "org.typelevel" %% "cats-core" % "1.1.0"
libraryDependencies += "org.typelevel" %% "cats-effect" % "0.10"

错误是
Error:(23, 22) could not find implicit value for parameter P: cats.Parallel[F,F]
List(foo, bar).parSequence

所以试试
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
}
}

当然可以介绍 type Parallel[F[_]] = cats.Parallel[F, F]然后这可以重写为 class ParallelExecIO[F[_]: ConcurrentEffect : Parallel] {...

关于scala - Cats 中的效果抽象和并行执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50232860/

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