2
作爲FP in Scala練習的一部分,我正在IndexedSeq
上執行foldLeft
。在IndexedSeq上實現foldLeft
我寫了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
的answer的+:
操作。它似乎是IndexedSeq
的班級或其父母的成員,因爲它沒有定義每個鏈接的帖子。
無論哪種方式更好(從性能或慣用斯卡拉的角度來看)?