首页 > 解决方案 > 如何使用没有类型别名的 Scala 猫对 Either 进行排序(请参阅 Herding cats)

问题描述

我在读《放牧猫》

Traverse 页面上的最后一个例子对我来说是失败的。

在示例中,他们这样做:-

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] 的关键隐式导入?

谢谢卡尔

标签: scalatraversalscala-cats

解决方案


您的代码缺少 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


推荐阅读