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) // 10All lessons in this course
- Thinking Recursively
- Accumulator Patterns
- foldLeft and foldRight
- reduce and aggregate