Scala での FPからの演習の一環として、私は on の実装に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)
}
EDITの回答+:
から演算子を取得したことに注意してください。リンクされた投稿ごとに定義せずに利用できるため、 のクラスまたはその親のメンバーのようです。dhgs
IndexedSeq
どちらの方が優れていますか (パフォーマンスまたは慣用的な Scala の観点から)?