假设我正在编写一个函数来压缩两个列表,只要它们具有相同的大小,否则会失败:
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
。你会如何改进上面的代码?
答案 0 :(得分:2)
如果由于某种原因你不喜欢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 zip(as: List[Int], bs: List[Int]): Either[String, List[(Int, Int)]] = {
@tailrec
def loop(as1: List[Int], bs1: List[Int], acc: List[(Int, Int)]): Either[String, List[(Int, Int)]] = (as1, bs1) match {
case (Nil, Nil) => Right(acc)
case (a :: as2, b :: bs2) => loop(as2, bs2, (a, b) :: acc)
case _ => Left(s"$as and $bs have different sizes")
}
loop(as, bs, Nil).map(_.reverse)
}