0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

reduce and aggregate

Other ways to combine elements.

From Fold to Reduce

Sometimes you want to combine elements without supplying a separate seed value.

reduce uses the first element as the starting accumulator and combines the rest into it.

It is a leaner cousin of fold for cases where the element type and result type are the same.

reduce Basics

reduce takes a binary function (a, b) and folds it across the collection, with no explicit initial value.

For a sum, it simply adds every element together.

val xs = List(1, 2, 3, 4)
val total = xs.reduce((a, b) => a + b)

@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