2015-10-18 9 views
1

任何人都可以告诉我,如果在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

尝试将rs匹配为Left还是Right? – Ashalynd

+0

多数民众赞成我正在努力实现,但我得到的例外 – MrX

+0

我认为不太可能的编译器将解决你的函数是tailrecursive。 for将解析成flatmap/Map并作为函数传递yield。它要求编译器稍微调整一下,这是一个尾部调用。 –

回答

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