関数型プログラミングの Scala演習に引き続き取り組みfoldRight
、IndexedSeq
型の実装に取り組んでいます。
foldRight は で評価されるright associativity
ため、パターン マッチング用に次の演算子を作成しました。
object :++ {
def unapply[T](s: Seq[T]) = s.lastOption.map(last =>
(last, s.take(s.length - 1)))
}
そして、次のように実装します。
object IndexedSeqFoldable extends Foldable[IndexedSeq] {
override def foldRight[A, B](as: IndexedSeq[A])(z: B)(f: (A, B) => B): B = {
def go(bs: Seq[A], acc: B): B = bs match {
case x :++ xs => go(xs, f(x, acc))
case _ => acc
}
go(as, z)
}
foldRight
で書くことができるという事実を無視してfoldLeft
、私のアプローチはどのように持ちこたえますか?