现在我更好地理解了你的问题,这很简单:
def takeLastSuccess[A, B](seq:Seq[ValidationNEL[A, B]]) =
seq.sequence[({type l[a] = ValidationNEL[A, a]})#l, B].map(_.last)
当您对这个 Scala 进行排序时,类型会出现一些问题,因此您需要使用类型 lambda。序列是从 Seq[Something[X]] 到 Something[Seq[X]] 的一个很好的捷径。最后,我们只是映射成功并从 B 的序列中获取最后一个 B。
从您引用的帖子中删除示例,这是我从 REPL 中得到的:
scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._
scala> type ExceptionsOr[A] = ValidationNEL[Exception, A]
defined type alias ExceptionsOr
scala> val successResults: Seq[ExceptionsOr[Int]] = Seq(
| "13".parseInt.liftFailNel, "42".parseInt.liftFailNel
| )
successResults: Seq[ExceptionsOr[Int]] = List(Success(13), Success(42))
scala> val failResults: Seq[ExceptionsOr[Int]] = Seq(
| "13".parseInt.liftFailNel, "a".parseInt.liftFailNel, "b".parseInt.liftFailNel
| )
failResults: Seq[ExceptionsOr[Int]] = List(Success(13), Failure(NonEmptyList(java.lang.NumberFormatException: For input string: "a")), Failure(NonEmptyList(java.lang.NumberFormatException: For input string: "b")))
scala> def takeLastSuccess[A, B](seq:Seq[ValidationNEL[A, B]]) = seq.sequence[({type l[a] = ValidationNEL[A, a]})#l, B].map(_.last)
takeLastSuccess: [A, B](seq: Seq[scalaz.Scalaz.ValidationNEL[A,B]])scalaz.Validation[scalaz.NonEmptyList[A],B]
scala> takeLastSuccess(successResults)
res0: scalaz.Validation[scalaz.NonEmptyList[Exception],Int] = Success(42)
scala> takeLastSuccess(failResults)
res1: scalaz.Validation[scalaz.NonEmptyList[Exception],Int] = Failure(NonEmptyList(java.lang.NumberFormatException: For input string: "a", java.lang.NumberFormatException: For input string: "b"))