【问题标题】:Traversing Either in Scala在 Scala 中遍历
【发布时间】:2018-09-16 21:02:12
【问题描述】:

我写了以下简单的代码:

import cats.effect.IO
import cats.instances.either._
import cats.syntax.TraverseSyntax

object Test extends App with TraverseSyntax{
  val e: Either[String, IO[Int]] = Right(IO(2))
  e.sequence //error here
}

不幸的是,它拒绝使用

Error:(25, 94) value sequence is not a member of scala.util.Either

你能解释一下原因吗?我导入了 either 实例,其中包括 Traverse[Either[A, ?]]。怎么了?

【问题讨论】:

  • 我还没有看到Either 遍历它是猫还是scalaz。你实际上想要实现什么?我怀疑你在寻找 .map 而不是 .traverse
  • @prayagupd 我要进行转换Either[String, F[Int]] --> F[Either[String, Int]]

标签: scala functional-programming scala-cats either


【解决方案1】:

除了 Kolmar 的回答(非常彻底)之外,我想提出一个替代且更简单的解决方案。

自 Scala 2.11.9 以来就有一个编译器标志,允许它识别具有多个类型参数的类型何时应该表现得像只有一个类型参数的类型。 我们称之为“部分统一”。

启用部分统一的最简单方法是添加sbt-partial-unification plugin。

如果您使用的是 Scala 2.11.9 或更高版本,您也可以简单地添加编译器标志:

scalacOptions += "-Ypartial-unification"

然后你的代码编译没有问题:

import cats.effect.IO
import cats.instances.either._
import cats.syntax.TraverseSyntax

object Test extends App with TraverseSyntax {
  val e: Either[String, IO[Int]] = Right(IO(2))
  e.sequence // No more error here
} 

在最近发布的 Scala 2.13 中,它现在是默认开启的,所以它应该可以开箱即用。

【讨论】:

  • 非常好。谢谢
【解决方案2】:

Traverse[F] 被定义为具有一个类型参数F[T] 的类型的类型类。 Either 类型有两个类型参数,因此 Scala 无法将转换应用到 Traverse.Ops 以对类型为 Either 定义的对象使用遍历语法方法。

为了使它们可用,您可以为Either 定义一个类型别名,它固定第一个类型参数的值,因此只有一个类型参数。然后,Scala 将能够对使用此类型别名定义的变量使用遍历语法:

type StringOr[T] = Either[String, T]
val e: StringOr[IO[Int]] = Right(IO(2))
e.sequence

另一种方法是使用类型 lambdas 或 kind projector compiler plugin 为您的类型获取 Traverse 的实例,然后在其上调用 sequence 方法并传递您的值:

val e: Either[String, IO[Int]] = Right(IO(2))

// With type lambda
Traverse[({ type L[T] = Either[String, T] })#L].sequence(e)

// With kind projector
Traverse[Either[String, ?]].sequence(e)

【讨论】:

    猜你喜欢
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2023-03-26
    • 2016-12-23
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多