在IndexedSeq上实现foldLeft

时间:2013-11-03 19:57:13

标签: scala

作为FP in Scala练习的一部分,我正致力于foldLeftIndexedSeq的实施。

我写了两个函数:

  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)
  }

编辑请注意,我从+:的{​​{3}}获得了dhgs运算符。它似乎是IndexedSeq的类或其父级的成员,因为它没有根据链接的帖子定义。

哪种方式更好(从性能或惯用的Scala角度来看)?

1 个答案:

答案 0 :(得分:0)

模式匹配肯定更具惯用性。

为了表现,它们应该大致相同,因为它们完全相同。

虽然只有基准测试会决定,而且这包括许多假设。