2

作为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 角度来看)?

4

1 回答 1

0

模式匹配肯定更惯用。

就性能而言,它们应该大致相同,因为它们完全相同。

虽然只有基准测试才能决定,这包括很多假设。

于 2013-11-03T19:59:44.703 回答