1

继续在 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我的方法如何成立?

4

0 回答 0