foldLeft and foldRight
Collapse collections to a value.
Folding a Collection
Folding collapses a collection into a single value by repeatedly combining elements with an accumulator.
The accumulator pattern you learned is exactly what fold abstracts. Instead of writing the recursive helper yourself, you pass in a starting value and a combining function.
foldLeft Basics
foldLeft takes an initial accumulator and a function (acc, element) and walks the collection from left to right.
At each step it replaces the accumulator with the function's result.
val xs = List(1, 2, 3, 4)
val total = xs.foldLeft(0)((acc, x) => acc + x)
@main def run(): Unit =
println(total) // 10All lessons in this course
- Thinking Recursively
- Accumulator Patterns
- foldLeft and foldRight
- reduce and aggregate