本文介绍了如何对没有类型别名的 Scala 猫进行排序(请参阅 Herding 猫)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读牧猫

遍历页面上的最后一个例子,对我来说失败了.

The final example on the Traverse page on sequencing List of Either failed for me.

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

in the example they do this:-

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)

但是当我尝试时出现以下错误:-

But When I try I get the following error:-

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 类型时,一切都很好:-

But when I help out the compiler with a type alias to fix the Left type all is good:-

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

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

So my question is how do I get the type inference to do the right thing to make the example work without having to introduce the type alias?

我是否遗漏了一个关键的隐式导入以使用任何 [A,B] ?

Have I missed a crucial implicit import to work with Either[A,B] ?

谢谢卡尔

推荐答案

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

Your code lacks scalac option -Ypartial-unification.

在 build.sbt 中你应该添加

In build.sbt you should add

scalaVersion := "2.12.6"

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

scalacOptions += "-Ypartial-unification"

或使用命令启动 Scala 控制台

or start Scala console with command

scala -Ypartial-unification

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

这篇关于如何对没有类型别名的 Scala 猫进行排序(请参阅 Herding 猫)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 23:49