如果任一函数返回 Left,则中断循环



在下面的代码中,我需要的是停止处理循环,如果either1either2返回 Left,如果发生这种情况,那么mainFunction也必须返回 Left。此外,either1.Lefteither2.Left返回的字符串需要由 mainFunction.Left 返回。如何做到这一点?

def either1 (i:Int): Future[Either[String,Int]] = Future {
                    if (i<3)
                       Right(i*2)
                    else
                       Left("error 1")
}
def either2 (i:Int): Future[Either[String,Int]] = Future {
                    if (i>3)
                       Right(i*2)
                    else
                       Left("error 2")
}

val seq = Seq ( 1,1,2,2,3,4,5 )
def mainFunction: Future[Either[String,Int]] = Future {
     val seq2 = seq.map { number =>
             if (number % 2 == 0)
                  either1(number) // <-- this needs to break the loop if it returns Left
             else
                  either2(number) // <-- this needs to break the loop if it returns Left
        }
    Right(seq2.length)  // <-- seq2 is a sequence of Futures
}

下面的代码不断迭代序列,直到遇到第一个错误,并返回错误消息或固定数字42(这是"它返回什么无关紧要"的要求(。

import scala.concurrent._
import scala.util._
import scala.concurrent.ExecutionContext.Implicits.global
def either1(i: Int): Future[Either[String,Int]] = Future {
  if (i < 3) Right(i * 2)
  else Left("error 1")
}
def either2 (i:Int): Future[Either[String,Int]] = Future {
  if (i > 3) Right(i * 2)
  else Left("error 2")
}
val seq = Seq(1, 1, 2, 2, 3, 4, 5)
val doesntMatter = 42
/** Returns either first error message returned by `either1` or
  * `either2`, or the fixed number `doesntMatter`.
  */
def mainFunction: Future[Either[String, Int]] = {
  def recHelper(remaining: List[Int]): Future[Either[String, Int]] = {
    remaining match {
      case Nil => Future { Right(doesntMatter) }
      case h :: t => (if (h % 2 == 0) either1(h) else either2(h)).flatMap {
        headEither =>
        headEither match {
          case Left(s) => Future { Left(s) }
          case Right(n) => recHelper(t)
        }
      }
    }
  }
  recHelper(seq.toList)
}
val res = mainFunction
Thread.sleep(2000)
println(res) // Future(Success(Left(error 2)))

如果你这样做的频率明显超过一次,请考虑看看 Scala Cats 的 BothT,以及专门为所有 monadic 类型类的此类用例定义的方法tailRecM

在 Scala 中,标准集合没有为此提供方法。你可以使用scala.util.control.Breaks,或者你必须编写递归,像这样

val seq = Seq(1, 1, 2, 2, 3, 4, 5)
def either1(i: Int): Either[String, Int] = {
    if (i < 3) Right(i * 2)
    else Left("error 1")
}
def either2(i: Int): Either[String, Int] = {
    if (i > 3) Right(i * 2)
    else Left("error 2")
}
def rec(seq: Seq[Int], acc: Seq[Either[String, Int]]): Seq[Either[String, Int]] = seq match {
    case Nil => acc
    case x :: xs =>
        val xx = if (x % 2 == 0) either1(x) else either2(x)
        xx match {
            case Left(_) => acc
            case Right(value) => rec(xs, acc :+ Right(value))
        }
    }
rec(seq, Seq())

如果库函数可以做我想做的事情,我通常会避免递归函数。

在这种情况下,我们可以使用takeWhile来获取所有Right的领先元素。但是,map调用仍将处理Seq的每个元素,因此您需要使用 view 来延迟评估:

val seq2 = seq.view.map { number =>
   if (number % 2 == 0)
     either1(number)
   else
     either2(number)
 }.takeWhile(_.isRight)

您仍然存在一个问题,即您的either函数实际上返回了一个Future,因此在它们完成之前无法测试LeftRight

最新更新