scala - 如何使用没有类型别名的 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] 的关键隐式导入?
谢谢卡尔
解决方案
您的代码缺少 scalac 选项-Ypartial-unification
。
在 build.sbt 你应该添加
scalaVersion := "2.12.6"
libraryDependencies += "org.typelevel" %% "cats-core" % "1.1.0"
scalacOptions += "-Ypartial-unification"
或使用命令启动 Scala 控制台
scala -Ypartial-unification
推荐阅读
- python - 当函数包含函数未使用的参数时,在函数中使用 kwargs
- apache-spark - pyspark Datetype() 在创建数据框期间
- c# - 上下文单击 Visual Studio 扩展中的本地菜单时恢复表达式
- python - 在 Jupyter Notebook 中导入可视化模块失败
- java - 制作第二行和第三行偏移的矩形网格?
- eclipse - 在黄瓜中获取 NoClassDefFoundError
- python - Pandas 计算按月和年分组的就业人数百分比
- android - 如何在 Android 客户端中获取 ga_session_id 和 ga_session_number?
- dart - Map.fromIterable 指定键/值提取 lambdas 的参数类型
- omnet++ - OMNET++ 是多线程还是单线程模型?