0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

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)  // 10

All lessons in this course

  1. Thinking Recursively
  2. Accumulator Patterns
  3. foldLeft and foldRight
  4. reduce and aggregate
← Back to Scala for Backend Engineering & Functional Programming