作为Scala 中 FP练习的一部分,我正在致力于foldLeft
实现IndexedSeq
.
我写了2个函数:
def foldLeft[A, B](as: IndexedSeq[A])(z: B)(f: (B, A) => B): B = {
def go(bs: IndexedSeq[A], acc: B): B = {
if (bs.isEmpty) acc
else go(bs.tail, f(acc, bs.head))
}
go(as, z)
}
然后,pattern match
方法:
def foldLeftPM[A, B](as: IndexedSeq[A])(z: B)(f: (B, A) => B): B = {
def go(bs: IndexedSeq[A], acc: B): B = bs match {
case x +: xs => go(xs, f(acc, x))
case _ => acc
}
go(as, z)
}
编辑请注意,我+:
从dhgs
's answer得到了操作员。它似乎是IndexedSeq
's 类或其父级的成员,因为它无需根据链接的帖子进行定义即可使用。
哪种方式更好(从性能或惯用的 Scala 角度来看)?