Scala猫和Either的遍历语法 - 不编译

问题描述 投票:4回答:1

我试图从猫库traverse使用sequence(或https://typelevel.org/cats/typeclasses/traverse.html,这与我的任务几乎相同)。我想用函数List[A]遍历A => Either[L,R]以获得Either[L,List[R]]

考虑以下微小的例子(我使用scala-2.12.6,cats-core-1.3.1,sbt-1.1.2):

import cats.implicits._

def isOdd(i: Int): Either[String, Int] = 
  if (i % 2 != 0) Right(i) else Left("EVEN")

val odd: Either[String, List[Int]] = (1 to 10).toList.traverse(isOdd)

它不编译,它给出:

no type parameters for method traverse: (f: Int => G[B])(implicit evidence$1: cats.Applicative[G])G[List[B]] exist so that it can be applied to arguments (Int => Either[String,Int])
[error]  --- because ---
[error] argument expression's type is not compatible with formal parameter type;
[error]  found   : Int => Either[String,Int]
[error]  required: Int => ?G[?B]
[error]     val odd: Either[String, List[Int]] = (1 to 10).toList.traverse(isOdd)

type mismatch;
[error]  found   : Int => Either[String,Int]
[error]  required: Int => G[B]
[error]     val odd: Either[String, List[Int]] = (1 to 10).toList.traverse(isOdd)
[error]                                                                   ^

could not find implicit value for evidence parameter of type cats.Applicative[G]
[error]     val odd: Either[String, List[Int]] = (1 to 10).toList.traverse(isOdd)
[error]                                                                   ^
scala applicative scala-cats
1个回答
1
投票

部分统一编译器标志是必需的。在scala 2.12中

scalacOptions += "-Ypartial-unification"添加build.sbt

谢谢托马斯

© www.soinside.com 2019 - 2024. All rights reserved.