scala - 如何使用没有类型别名的 Scala 猫对 Either 进行排序(请参阅 Herding cats)

标签 scala traversal scala-cats

我正在阅读 Herding Cats

Traverse page 上的最后一个示例对我来说,Either 的排序列表失败了。

在示例中他们这样做:-

scala> List(Right(1): Either[String, Int]).sequence
res5: Either[String,List[Int]] = Right(List(1))
scala> List(Right(1): Either[String, Int], Left("boom"): Either[String, Int]).sequence
res6: Either[String,List[Int]] = Left(boom)

但是当我尝试我得到以下错误:-

scala> import cats._, cats.data._, cats.implicits._
scala> val les = List(Right(3):Either[String,Int], Right(2):Either[String,Int])
scala> les.sequence
<console>:37: error: Cannot prove that Either[String,Int] <:< G[A].
les.sequence
   ^

但是当我用类型别名帮助编译器修复 Left 类型时,一切都很好:-

scala> type XorStr[X] = Either[String,X]
defined type alias XorStr

scala> val les = List(Right(3):XorStr[Int], Right(2):XorStr[Int])
les: List[XorStr[Int]] = List(Right(3), Right(2))

scala> les.sequence
res0: XorStr[List[Int]] = Right(List(3, 2))

所以我的问题是如何让类型推断做正确的事情以使示例工作而不必引入类型别名?

我是否错过了使用 Either[A,B] 的关键隐式导入?

谢谢 卡尔

最佳答案

您的代码缺少 scalac 选项 -Ypartial-unification

在 build.sbt 你应该添加

scalaVersion := "2.12.6"

libraryDependencies += "org.typelevel" %% "cats-core" % "1.1.0"

scalacOptions += "-Ypartial-unification"

或使用命令启动 Scala 控制台

scala -Ypartial-unification

http://eed3si9n.com/herding-cats/partial-unification.html

关于scala - 如何使用没有类型别名的 Scala 猫对 Either 进行排序(请参阅 Herding cats),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499152/

相关文章:

scala - 整数对的尾递归有界流(Scala)?

java - TinkerPop3 在遍历期间更新图

c++ - 遍历一棵 n 叉树

scala - 猫,减少 EitherT 的 Seq

scala - 在自由 monad 中使用 Either

从 Boolean 列表到求和 Int 列表的 Scala 匹配

scala - 将 JVM 参数传递给 SBT

mysql - 事务 block |星火SQL,RDD

javascript - 根据 sibling 之前或之后查找项目

scala - 将函数列表应用于值的简单方法