14

假设你有一堆方法:

def foo() : Try[Seq[String]]
def bar(s:String) : Try[String]

并且您想要理解:

for {
  list <- foo
  item <- list
  result <- bar(item)
} yield result

当然这不会编译,因为在这种情况下 Seq 不能与 Try 一起使用。

任何人都有一个很好的解决方案,如何在不将其分成单独的两个 for 的情况下编写干净的代码?

我已经第三次遇到这个语法问题,并认为是时候问这个问题了。

4

3 回答 3

6

恕我直言:Try and Seq不仅仅是定义 monad 转换器所需的:

库代码:

case class trySeq[R](run : Try[Seq[R]]) {
  def map[B](f : R => B): trySeq[B] = trySeq(run map { _ map f })
  def flatMap[B](f : R => trySeq[B]): trySeq[B] = trySeq {
    run match {
      case Success(s) => sequence(s map f map { _.run }).map { _.flatten }
      case Failure(e) => Failure(e)
    }
  }

  def sequence[R](seq : Seq[Try[R]]): Try[Seq[R]] = {
    seq match {
      case Success(h) :: tail =>
        tail.foldLeft(Try(h :: Nil)) {
          case (Success(acc), Success(elem)) => Success(elem :: acc)
          case (e : Failure[R], _) => e
          case (_, Failure(e)) => Failure(e)
        }
      case Failure(e) :: _  => Failure(e)
      case Nil => Try { Nil }
    }
  }
}

object trySeq {
  def withTry[R](run : Seq[R]): trySeq[R] = new trySeq(Try { run })
  def withSeq[R](run : Try[R]): trySeq[R] = new trySeq(run map (_ :: Nil))

  implicit def toTrySeqT[R](run : Try[Seq[R]]) = trySeq(run)
  implicit def fromTrySeqT[R](trySeqT : trySeq[R]) = trySeqT.run
} 

并且在您可以使用 for-comrehension 之后(只需导入您的库):

def foo : Try[Seq[String]] = Try { List("hello", "world") } 
def bar(s : String) : Try[String] = Try { s + "! " }

val x = for {
  item1  <- trySeq { foo }
  item2  <- trySeq { foo }
  result <- trySeq.withSeq { bar(item2) }
} yield item1 + result

println(x.run)

它适用于:

def foo() = Try { List("hello", throw new IllegalArgumentException()) } 
// x = Failure(java.lang.IllegalArgumentException)
于 2014-04-24T11:39:32.513 回答
4

您可以利用Try可以转换为OptionOption的事实Seq

for {
  list <- foo.toOption.toSeq // toSeq needed here, as otherwise Option.flatMap will be used, rather than Seq.flatMap
  item <- list
  result <- bar(item).toOption // toSeq not needed here (but allowed), as it is implicitly converted
} yield result

这将返回 a (可能为空,如果Trys 失败) Seq

如果要保留所有异常详细信息,则需要一个Try[Seq[Try[String]]]. 这不能用单一的理解来完成,所以你最好坚持使用 plain map

foo map {_ map bar}

如果你想以不同的方式混合你Try的 s 和Seqs ,事情会变得更复杂,因为没有自然的方法可以使 s 变平Try[Seq[Try[String]]]。@Yury 的回答展示了您必须做的事情。

或者,如果您只对代码的副作用感兴趣,您可以这样做:

for {
  list <- foo
  item <- list
  result <- bar(item)
} result

这是有效的,因为foreach具有较少限制的类型签名。

于 2014-04-24T10:22:28.323 回答
2

Try 可以转换为 Option,然后您可以将其用于理解。例如

scala> def testIt() = {
     |   val dividend = Try(Console.readLine("Enter an Int that you'd like to divide:\n").toInt)
     |   dividend.toOption
     | }
testIt: ()Option[Int]

scala> for (x <- testIt()) println (x * x)
Enter an Int that you'd like to divide:

scala> for (x <- testIt()) println (x * x)
Enter an Int that you'd like to divide:
1522756

我第一次输入“w”,然后第二次输入 1234。

于 2014-04-24T10:10:01.337 回答