Updated March 28, 2023
Introduction to Scala foldLeft
Scala foldLeft function can be used with the collection data structure in scala. Also, foldLeft is applicable for both immutable and mutable data structures of collection. This function takes two arguments as parameters. One is the binary operator and the second argument of the collection always points to the current elements of the collection. This binary operator is used to settle the elements of the collection.
Syntax of Scala foldLeft:
This method takes two arguments as a parameter, and it traverses from left to right, so it is named as the foldLeft() method.
Below is the syntax of the method defined by the scala community, which is as follows. In the next line, we have one practice example to better understand the foldLeft function in scala.
def foldLeft[B](z: B)(op: (B, A) ⇒ B): B
Example:
val result = list.foldLeft(1.1)(_ + _)
In this, we give the initial value to the function as 1.1 and try to sum all the elements present in the list. This can be applied to any collection data structure.
How foldLeft Function works in Scala?
foldLeft function traverse the element of collection data structure from left to right to it is named as foldLeft() function in scala. It takes two parameters, and also we can specify the initial value by using this function. This function is a recursive function and helps us from stack-overflow exceptions while programming.
This function is the member function of TraversableOnce in scala. TraversableOnce is a trait built to remove the duplicate code of Traversable and Iterator, which implements the common functions. This trait also contains abstract methods, and the Traversable and Iterator provide this abstract method implementation.
Now we will see one example where we will initialize our list of elements and trying to apply the foldLeft function on it.
Example:
Code:
val myList: Seq[Int] = Seq(10, 30, 50, 60)
println(myList)
In this, we are creating one Sequence of integers containing around 4 variables and trying to print out the sequence elements.
Code:
val result = myList.foldLeft(0)(_ + _)
println("result is ::" + result)
After creating the sequence, now we want to sum all the elements present inside the sequence. For this, we are using the foldLeft function. First, we call foldLeft on our collection, followed by the initial value that we have assigned as 0. After that, we use the binary operator + to get the sum of all elements present inside the collection sequence. We can use any binary operator here depend upon the requirement.
We can also use the foldLeft function with string type of collection data structure; we will see one example.
Here we are creating one List if string that contains so many elements into it. After that, we are just printing our newly created list that all.
Example:
Code:
val myList: List[String] = List("amit", "sumit", "vinit", "lalti", "minit")
println(myList)
Example:
Code:
println(s"using special charcter = ${myList.foldLeft("")((x, y) => x + y + " ********* ")}")
Now we are trying to add some string after our every element present into the for this, we are using the foldLeft function, and inside this function, we are appending the string that we want to show.
We can also pass a function obtained value directly to the foldLeft function to concatenate the string.
Example:
Code:
val myList: List[String] = List("amit", "sumit", "vinit", "lalti", "minit")
println(myList)
val valFun: (String, String) => String = (a, b) => a + b + " Donut "
var result = myList.foldLeft("")(valFun)
println(result)
So in the above example, we are passing the value function directly to the foldLeft function. It is just a simple way and more readable to the developer. But i would recommend the first approach to follow.
Examples of Scala foldLeft
Given below are the examples of Scala foldLeft:
Example #1
In this example, we are modifying the string list elements by using the foldLeft function in scala.
Code:
object Main extends App{
// Your code here!
val myList: List[String] = List("amit", "sumit", "vinit", "lalti", "minit")
println("list before foldLeft function is :::: ")
println(myList)
var result = myList.foldLeft("")((x, y) => x + y + " ********* ")
println("list after foldLeft function is :::: ")
println(result)
//println(s"using special character = ${myList.foldLeft("")((x, y) => x + y + " ********* ")}")
}
Output:
Example #2
In this example, we are finding the sum of all the elements present inside the List collection data structure.
Code:
object Main extends App{
// Your code here!
val myList: List[Int] = List(100, 200, 300, 400, 500, 600, 700)
println("list before foldLeft function is :::: ")
println(myList)
var result = myList.foldLeft(0)(_+_)
println("list after foldLeft function is :::: ")
println(result)
//println(s"using special character = ${myList.foldLeft("")((x, y) => x + y + " ********* ")}")
}
Output:
Example #3
In this example, we are applying different binary operators on the list of integers by using the foldLeft function.
Code:
object Main extends App{
// Your code here!
val myList: List[Int] = List(100, 200, 300, 400, 500, 600, 700)
println("list before foldLeft function is :::: ")
println(myList)
var result = myList.foldLeft(0)(_-_)
println("list after foldLeft function is :::: ")
println(result)
var result1 = myList.foldLeft(0)(_*_)
println("list after foldLeft function is :::: ")
println(result1)
//println(s"using special character = ${myList.foldLeft("")((x, y) => x + y + " ********* ")}")
}
Output:
Example #4
In this example, we are finding the maximum value of the collection by using the max function inside the foldLeft function available in scala.
Code:
object Main extends App{
// Your code here!
val myList: List[Int] = List(100, 200, 300, 400, 500, 600, 700)
println("list before foldLeft function is :::: ")
println(myList)
var result = myList.foldLeft(0)(_ max _)
println("list after foldLeft function is :::: ")
println(result)
//println(s"using special character = ${myList.foldLeft("")((x, y) => x + y + " ********* ")}")
}
Output:
Conclusion
foldLeft functions traverse each element of the collection data structure and help us to perform operations on the element. Thus, it is more reduced and simplified, and untestable to the programmers. Also, it reduces the number of lines of code.
Recommended Articles
This is a guide to Scala foldLeft. Here we discuss the introduction, how the foldLeft function works in scala? And examples respectively. You may also have a look at the following articles to learn more –