1
給定一個List[Either[A,B]]
,我可以使用sequence
在Haskell,用於提取整個Right[B]
S或Left[A]
的List
。序列樣功能Scala中
Prelude> sequence [Left "bad", Right 555]
Left "bad"
Prelude> sequence [Right 4534, Right 555]
Right [4534,555]
我不知道,如果這種方法適合的sequence
的定義,但它是處理List[Either[A,B]] => Either[A, List[B]]
一個狹窄的功能。
scala> def f[A, B](es: List[Either[A, B]]): Either[A, List[B]] = es match {
| case Right(x) :: xs => f(xs).right.map(y => x :: y)
| case Nil => Right(Nil)
| case left @ Left(_) :: _ => left
| }
但我收到這個錯誤,我不明白。
<console>:10: error: type mismatch;
found : scala.collection.immutable.::[Either[?A3,?B3]] where type ?B3 <: B (this is a GADT skolem), type ?A3 <: A (this is a GADT skolem)
required: Either[A,List[B]]
case left @ Left(_) :: _ => left
^
我在做什麼錯在這裏?