Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

traversal - How to sequence Either with Scala cats without a type alias (see Herding cats)

I was reading Herding Cats

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
   ^

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?

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

Thanks Karl

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code lacks scalac option -Ypartial-unification.

In build.sbt you should add

scalaVersion := "2.12.6"

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

scalacOptions += "-Ypartial-unification"

or start Scala console with command

scala -Ypartial-unification

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...