Blog

Functional Snippet #5: Reduce

One of the most popular functions among functional programmers is reduce (in other languages also sometimes known as fold). The reduce function operates on an array, takes an initial value, and combines each element with that value. For example, to sum an array of integers, we can define a function sum that takes an initial value of 0 and then combines the intermediate results using the + operator.

let sum: [Int] -> Int = { $0.reduce(0, combine: +) }

To calculate the product, we can use the same approach with an initial value of 1 and the multiplication operator.

let product: [Int] -> Int = { $0.reduce(1, combine: *) }

However, reduce does not just work on lists of integers. We could also write a function that checks if all Bools in a list are true.

let all: [Bool] -> Bool = { $0.reduce(true, combine: { $0 && $1 }) }

Reduce is very flexible, and you can use it on lists with any element type. It is even possible to define map and filter in terms of reduce, which is a good exercise if you’d like some practice.

Stay up-to-date with our newsletter or follow us on Twitter.

Back to the Blog

recent posts