Scala foldLeft and foldRight functions

In this post, I am going to give some examples which explain how to use foldLeft and foldRight functions.

def foldLeft[B](z: B)(op: (B, A) ⇒ B): B – Applies a binary operator to a start value and all elements of this sequence, going left to right.

def foldRight[B](z: B)(op: (A, B) ⇒ B): B – Applies a binary operator to all elements of this list and a start value, going right to left.

Assume that you have a list and you want to add/multiply all the elements. We can use foldLeft function to do that. The order of traversing a list is from left to right. We can specify the initial value as well. Refer the below example.


object ScalaEx {
  def main(args: Array[String]): Unit = {

    val list = List(10, 10, 5)
    val total = list.foldLeft(1) {
      _ * _
    }
    println(s"Total::$total")

    val names = List("name1", "name2", "name3")
    val allNames = names.foldLeft("")((x, y) => x + " " + y)
    println(s"allNames::$allNames")
  }

}

The output is given below,



Total::500
allNames:: name1 name2 name3

In the above example, we have used foldLeft to multiply the value of a list and then reduce it to a single value and join a list.

The foldRight works the same way but the order of traversing a list is from right to left. Refer the below example to know it.



object ScalaEx {
  def main(args: Array[String]): Unit = {

    val names = List("name1", "name2", "name3")
    val allNamesFR = names.foldRight("")( (elem, acc) => acc + " " + elem )
    println(s"allNames with foldRight::$allNamesFR")

    val allNamesFL = names.foldLeft("")( (acc, elem) => acc + " " + elem )
    println(s"allNames with foldLeft::$allNamesFL")

  }

}


The output is given below,


allNames with foldRight:: name3 name2 name1
allNames with foldLeft:: name1 name2 name3


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s