16

有没有一种简单的方法来展平一组 try 以给出 try 值的成功,或者只是失败?例如:

def map(l:List[Int]) = l map {
  case 4 => Failure(new Exception("failed"))
  case i => Success(i)
}

val l1 = List(1,2,3,4,5,6)
val result1 = something(map(l1))

result1: Failure(Exception("failed"))

val l2 = List(1,2,3,5,6)
val result2 = something(map(l2)) 

result2: Try(List(1,2,3,5,6))

您将如何处理集合中的多个故障?

4

7 回答 7

29

对于失败优先操作,这非常接近最低限度:

def something[A](xs: Seq[Try[A]]) =
  Try(xs.map(_.get))

(到了你不应该费心创建方法的地步;只需使用Try)。如果你想要所有的失败,一个方法是合理的;我会使用Either

def something[A](xs: Seq[Try[A]]) =
  Try(Right(xs.map(_.get))).
  getOrElse(Left(xs.collect{ case Failure(t) => t }))
于 2013-03-19T13:00:07.800 回答
9

少一点冗长,更安全:

def sequence[T](xs : Seq[Try[T]]) : Try[Seq[T]] = (Try(Seq[T]()) /: xs) {
    (a, b) => a flatMap (c => b map (d => c :+ d))
}

结果:

sequence(l1)

res8: scala.util.Try[Seq[Int]] = Failure(java.lang.Exception: failed)

sequence(l2)

res9: scala.util.Try[Seq[Int]] = Success(List(1, 2, 3, 5, 6))

于 2013-03-19T10:55:55.780 回答
8

也许不像您希望的那么简单,但这有效:

def flatten[T](xs: Seq[Try[T]]): Try[Seq[T]] = {
  val (ss: Seq[Success[T]]@unchecked, fs: Seq[Failure[T]]@unchecked) =
    xs.partition(_.isSuccess)

  if (fs.isEmpty) Success(ss map (_.get))
  else Failure[Seq[T]](fs(0).exception) // Only keep the first failure
}

val xs = List(1,2,3,4,5,6)
val ys = List(1,2,3,5,6)

println(flatten(map(xs))) // Failure(java.lang.Exception: failed)
println(flatten(map(ys))) // Success(List(1, 2, 3, 5, 6))

partition请注意,正如注释所证明的那样,使用的类型并不安全@unchecked。在这方面,foldLeft累积两个序列Seq[Success[T]]的aSeq[Failure[T]]会更好。

如果你想保留所有的失败,你可以使用这个:

def flatten2[T](xs: Seq[Try[T]]): Either[Seq[T], Seq[Throwable]] = {
  val (ss: Seq[Success[T]]@unchecked, fs: Seq[Failure[T]]@unchecked) =
    xs.partition(_.isSuccess)

  if (fs.isEmpty) Left(ss map (_.get))
  else Right(fs map (_.exception))
}

val zs = List(1,4,2,3,4,5,6)

println(flatten2(map(xs))) // Right(List(java.lang.Exception: failed))
println(flatten2(map(ys))) // Left(List(1, 2, 3, 5, 6))
println(flatten2(map(zs))) // Right(List(java.lang.Exception: failed, 
                           //            java.lang.Exception: failed))
于 2013-03-19T10:29:48.067 回答
6

作为对 Impredicative 的回答和评论的补充,如果您的依赖项中同时具有scalaz-7scalaz-contrib /scala210 :

> scala210/console
[warn] Credentials file /home/folone/.ivy2/.credentials does not exist
[info] Starting scala interpreter...
[info] 
Welcome to Scala version 2.10.0 (OpenJDK 64-Bit Server VM, Java 1.7.0_17).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.util._
import scala.util._

scala> def map(l:List[Int]): List[Try[Int]] = l map {
     |   case 4 => Failure(new Exception("failed"))
     |   case i => Success(i)
     | }
map: (l: List[Int])List[scala.util.Try[Int]]

scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._

scala> import scalaz.contrib.std.utilTry._
import scalaz.contrib.std.utilTry._

scala> val l1 = List(1,2,3,4,5,6)
l1: List[Int] = List(1, 2, 3, 4, 5, 6)

scala> map(l1).sequence
res2: scala.util.Try[List[Int]] = Failure(java.lang.Exception: failed)

scala> val l2 = List(1,2,3,5,6)
l2: List[Int] = List(1, 2, 3, 5, 6)

scala> map(l2).sequence
res3: scala.util.Try[List[Int]] = Success(List(1, 2, 3, 5, 6))

您需要 scalaz 来获取(隐藏在Applicative 实例中)的实例,以获取方法。您需要 scalaz-contrib 的实例,这是的类型签名所必需的。 存在于 scalaz 之外,因为它只出现在 scala 2.10 中,并且 scalaz 旨在交叉编译到早期版本)。ListMonadPlussequenceTraverse TrysequenceTry

于 2013-03-19T12:59:55.633 回答
5

从 开始Scala 2.13,大多数集合都提供了一种partitionMap方法,该方法基于返回Right或的函数来划分元素Left

在我们的例子中,我们可以调用一个将s 转换为s ( )partitionMap的函数,以便将es 划分为s 并将s 划分为s。TryEitherTry::toEitherSuccessRightFailureLeft

然后,只需根据是否存在左侧来匹配生成的左侧和右侧分区元组:

tries.partitionMap(_.toEither) match {
  case (Nil, rights)       => Success(rights)
  case (firstLeft :: _, _) => Failure(firstLeft)
}
// * val tries = List(Success(10), Success(20), Success(30))
//       => Try[List[Int]] = Success(List(10, 20, 30))
// * val tries = List(Success(10), Success(20), Failure(new Exception("error1")))
//       => Try[List[Int]] = Failure(java.lang.Exception: error1)

中间partitionMap步骤的详细信息:

List(Success(10), Success(20), Failure(new Exception("error1"))).partitionMap(_.toEither)
// => (List[Throwable], List[Int]) = (List(java.lang.Exception: error1), List(10, 20))
于 2019-01-19T23:53:05.243 回答
3

看看liftweb Box monad。在tryo构造函数的帮助下,它为您提供了您正在寻找的抽象。

有了tryo您可以将功能提升到Box. 然后,该框要么包含函数的结果,要么包含错误。然后,您可以使用通常的 monadic 辅助函数(flatMap、filter 等)访问该框,而无需担心该框是否包含错误或函数的结果。

例子:

import net.liftweb.util.Helpers.tryo

List("1", "2", "not_a_number") map (x => tryo(x.toInt)) map (_ map (_ + 1 ))

结果到

List[net.liftweb.common.Box[Int]] = 
  List(
    Full(2), 
    Full(3), 
    Failure(For input string: "not_a_number",Full(java.lang.NumberFormatException: For input string: "not_a_number"),Empty)
  )

您可以跳过错误的值flatMap

List("1", "2", "not_a_number") map (x => tryo(x.toInt)) flatMap (_ map (_ + 1 ))

结果

List[Int] = List(2, 3)

还有多种其他辅助方法,例如用于组合框(在链接错误消息时)。你可以在这里找到一个很好的概述:Box Cheat Sheet for Lift

您可以单独使用它,无需使用整个升降机框架。对于上面的示例,我使用了以下 sbt 脚本:

scalaVersion := "2.9.1"

libraryDependencies += "net.liftweb" %% "lift-common" % "2.5-RC2"

libraryDependencies += "net.liftweb" %% "lift-util" % "2.5-RC2"
于 2013-03-19T12:23:04.787 回答
0

这些是我的 2cents:

def sequence[A, M[_] <: TraversableOnce[_]](in: M[Try[A]])
  (implicit cbf:CanBuildFrom[M[Try[A]], A, M[A]]): Try[M[A]] = {
    in.foldLeft(Try(cbf(in))) {
      (txs, tx) =>
        for {
          xs <- txs
          x <- tx.asInstanceOf[Try[A]]
        } yield {
          xs += x
        }
    }.map(_.result())
  }
于 2014-02-08T12:22:40.483 回答