2

As part of an exercise from FP in Scala, I'm working on the implementation of foldLeft on an IndexedSeq.

I wrote 2 functions:

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

And, then the pattern match way:

  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 Note that I got the +: operator from dhgs's answer. It appears to be a member of IndexedSeq's class or its parent since it's available without defining per the linked post.

Is either way better (from a performance or idiomatic Scala point of view)?

Community
  • 1
  • 1
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

1 Answers1

0

The pattern match is definitely more idiomatic.

For performance, they should be about the same, since they are exactly equivalent.

Though only benchmarking would decide, and that includes a lot of assumptions.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285