Explain foldLeft along with code.
The foldLeft function in Scala’s collections iterates from left to right across a collection’s items, applying an accumulator and a binary operation to each member. It has the definition (z: B)(op: (B, A) => B): B, where op is the binary operator and z is the starting value.
object Main {
def main(args: Array[String]): Unit = {
val list = List(1, 2, 3, 4, 5)
val sum = list.foldLeft(0)((acc, elem) => acc + elem)
println(sum) // Output: 15
}
}
The foldLeft function in this example takes a starting value of 0 and adds each element in the list to it, yielding the total of all the items.
Output
What are Folding Lists in Scala?
A basic operation in functional programming, which includes Scala, is folding lists. It enables you to use a binary operation to merge the components of a collection. This operation applies the action to each member of the collection iteratively, building up a result from the original value.
Table of Content
- 1. What is a folding list in Scala?
- 2. Explain foldLeft along with code.
- 3. Explain foldRight with code.
- 4. Explain fold.
- 5. Explain the Difference using Parallelism and Method Signature.
- 6. Conclusion
- 7. FAQs
Contact Us