【发布时间】:2014-08-21 13:40:34
【问题描述】:
我需要在 Scala 中实现一个"zipLongest" 函数;也就是说,将两个序列组合成对,如果一个比另一个长,则使用默认值。 (与标准的zip 方法不同,它只会截断到最短的序列。)
我直接实现如下:
def zipLongest[T](xs: Seq[T], ys: Seq[T], default: T): Seq[(T, T)] = (xs, ys) match {
case (Seq(), Seq()) => Seq()
case (Seq(), y +: rest) => (default, y) +: zipLongest(Seq(), rest, default)
case (x +: rest, Seq()) => (x, default) +: zipLongest(rest, Seq(), default)
case (x +: restX, y +: restY) => (x, y) +: zipLongest(restX, restY, default)
}
有没有更好的方法?
【问题讨论】:
标签: scala collections functional-programming