Scala 如何仅在列表大小相同时压缩列表,而在列表大小不同时压缩列表失败?

Scala 如何仅在列表大小相同时压缩列表,而在列表大小不同时压缩列表失败?,scala,collections,Scala,Collections,假设我正在编写一个函数,仅当两个列表大小相同时才压缩它们,否则将失败: def foo(xs: List[Int], ys: List[Int]): Either[String, List[(Int, Int)]] = if (xs.size == ys.size) Right(xs zip ys) else Left(s"$xs and $ys have different sizes") 它可以工作,但我不喜欢使用if。如何改进上述代码?如果出于某种原因您不喜欢if def zi

假设我正在编写一个函数,仅当两个列表大小相同时才压缩它们,否则将失败:

 def foo(xs: List[Int], ys: List[Int]): Either[String, List[(Int, Int)]] =
    if (xs.size == ys.size) Right(xs zip ys) else Left(s"$xs and $ys have different sizes")

它可以工作,但我不喜欢使用
if
。如何改进上述代码?

如果出于某种原因您不喜欢
if

def zip(as: List[Int], bs: List[Int]): Either[String, List[(Int, Int)]] = (as, bs) match {
    case (Nil, Nil) => Right(Nil)
    case (a :: as1, b :: bs1) => for {
      t <- zip(as1, bs1)
    } yield (a, b) :: t
    case _ =>  Left(s"$as and $bs have different sizes")
  }

如果出于某种原因您不喜欢
if

def zip(as: List[Int], bs: List[Int]): Either[String, List[(Int, Int)]] = (as, bs) match {
    case (Nil, Nil) => Right(Nil)
    case (a :: as1, b :: bs1) => for {
      t <- zip(as1, bs1)
    } yield (a, b) :: t
    case _ =>  Left(s"$as and $bs have different sizes")
  }

我觉得不错。无论如何,您必须使用条件。另一种选择可能是在大小上进行模式匹配,但我认为它不会带来太多价值
def foo(xs:List[Int],ys:List[Int]):或者[String,List[(Int,Int)]]=xs.size==ys.size匹配{case true=>Right(xs-zip-ys)case false=>Left(s“$xs和$ys有不同的大小”)}
对我来说很好。无论如何,您必须使用条件。另一种选择是在大小上进行模式匹配,但我认为它不会带来太大的价值
def foo(xs:List[Int],ys:List[Int]):或者[String,List[(Int,Int)]]=xs.size==ys.size匹配{case true=>Right(xs-zip-ys)case false=>Left(s“$xs和$ys有不同的大小”)