简体   繁体   中英

Implementation of foldLeft in Scala

TraversableOnce implements foldLeft with mutable var result .

def foldLeft[B](z: B)(op: (B, A) => B): B = {
   var result = z
   this foreach (x => result = op(result, x))
   result
}

I understand that it is not practical to implement foldLeft recursively. Now I wonder if it is possible to implement foldLeft without mutable variables efficiently.

Can it be done? Why if it cannot?

Tail-recursion is your friend:

def foldLeft[A, B](xs: Seq[A], z: B)(op: (B, A) => B): B = {
  def f(xs: Seq[A], acc: B): B = xs match {
    case Seq()   => acc
    case x +: xs => f(xs, op(acc, x))
  }
  f(xs, z)
}

Btw, TraversableOnce doesn't implement head or tail , the only way to access the elements is to use foreach .

object FoldImplement:
  def myFoldLeft(lst: List[Int])(acc: Int)(f: (Int, Int)=>Int): Int =
    lst match
      case List() => acc
      case hd::tl => myFoldLeft(tl)(f(hd,acc))(f)

  @main def runFoldImpl =
    println(myFoldLeft(List(1,3,5))(0)((acc,elem)=>acc+elem))
def foldLeft[B](z: B)(op: (B, A) => B): B = {
  val thislist = this.toList
  @tailrec
  def myFold(result: B, list: List[A]): B = list match {
    case Nil => result
    case head :: tail => myFold(op(result,head), tail)
  }
  myFold(z, thislist)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM