任何人都可以告诉我在Scala中是否可以使用以下语法编写某些内容?
@annotation.tailrec
def traverse[E,A,B](es: List[A])(f: A => Either[E, B]): Either[E, List[B]] = {
def go(es: List[A], rs: Either[E, List[B]]): Either[E, List[B]] = {
es match {
case Nil => rs
case x::xs => for {
Right(b) <- f(x);
Right(ls) <- rs
} yield go(xs, Right(b::ls))
}
}
go(es, Right(List()))
}
我不断收到以下语法异常
Error:(47, 12) constructor cannot be instantiated to expected type;
found : A$A400.this.Right[A]
required: List[?B3] where type ?B3 <: B (this is a GADT skolem)
Right(ls) <- rs
^
答案 0 :(得分:1)
说实话,我并不完全确定该功能的目的是什么,但是,猜测f
是什么,这里有什么东西可以做你想要的?
@annotation.tailrec
def f[A, B, E](e: A): Either[E, B] = ???
def go[A, B, E](es: List[A], rs: Either[E, List[B]]): Either[E, List[B]] = {
es match {
case Nil => rs
case x :: xs => (f(x), rs) match {
case (Right(b), Right(ls)) => go(xs, Right(b :: ls))
}
}
go(es, Right(List()))
}