Conceptintro
Map, filter and reduce
Also called map, filter, reduce, fold, map-reduce, apply-to-all, accumulate, aggregate, select and where.
Map, filter and reduce are three higher-order functions on collections. Map changes each element, filter keeps the elements that pass a test, and reduce combines all elements into one value.
- Applies to
- core-languages
Idea
Map, filter and reduce are three functions that take a function and a collection. Each one replaces a common kind of loop.
- Map "applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type."1
- Filter produces a new collection "containing exactly those elements of the original data structure for which a given predicate returns the Boolean value true."2
- Reduce, also called fold, combines the elements into one value. "Fold is also termed as reduce, accumulate, aggregate, compress, or inject."3
from functools import reduce
nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda x: x * x, nums)))
print(list(filter(lambda x: x % 2 == 0, nums)))
print(reduce(lambda acc, x: acc + x, nums, 0))
evens = filter(lambda x: x % 2 == 0, nums)
squares = map(lambda x: x * x, evens)
print(reduce(lambda acc, x: acc + x, squares, 0))
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
21
56
The last three lines join the three functions. Filter keeps 2, 4 and 6, map squares them to 4, 16 and 36, and reduce adds them to 56.
How it works
- Map. The function takes one element and returns one new element. The result has the same number of elements as the input. In Python,
mapwill "Return an iterator that applies function to every item of iterable, yielding the results."4 - Filter. The function is a predicate: it takes one element and returns true or false. Python
filterwill "Construct an iterator from those elements of iterable for which function is true."4 - Reduce. The function takes two values: the result so far, often called the accumulator, and the next element. Python
reducewill "Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value."5 An initial value starts the accumulator and is the result for an empty collection. - Left and right folds. The order of the combination can change the result. "With a right fold, the sum would be parenthesized as 1 + (2 + (3 + (4 + 5))), whereas with a left fold it would be parenthesized as (((1 + 2) + 3) + 4) + 5."3 For an associative operation such as
+, both give the same value3.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Idiom | |
| Rust | Standard library | |
| Kotlin | Native | Kotlin collections have the functions map, filter, reduce and fold, and a lambda gives the operation. No example file exists because kotlinc is not installed. |
| SQL | Idiom | The SELECT list computes a value for each row, the WHERE clause keeps the rows that pass a test and aggregate functions such as SUM combine the rows. SQL has no function values, so these are clauses, not higher-order functions. |
| Bash | Idiom | |
| PowerShell | Idiom | The cmdlets ForEach-Object and Where-Object map and filter the objects in a pipeline, and a loop or Measure-Object combines them. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is a markup language and has no functions. |
| CSS | Does not apply | CSS has no collections of values that a function can map, filter or reduce. |
| Regular expressions | Does not apply | A regular expression has no functions and no collections. |
- Python. The built-in functions
mapandfilter, andfunctools.reduce45. Python 3 movedreduceout of the built-in functions. The release notes say: "Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable."6 - JavaScript. The array methods
map,filterandreduce.map"creates a new array populated with the results of calling a provided function on every element in the calling array."7filter"creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function."8reduceruns "a user-supplied "reducer" callback function on each element of the array"9. - TypeScript. The same array methods as JavaScript, with types for the callbacks.
- Java. Streams. The package has "functional-style operations on streams of elements, such as map-reduce transformations on collections."10 "A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation"10.
- C#. LINQ. The method
Selectis theselectclause andWhereis thewhereclause of a query expression11.Aggregate"Applies an accumulator function over a sequence."12 - C++. The algorithms
std::transform,std::copy_ifandstd::accumulate.std::transform"Applies the given function to the elements of the given source range(s), and stores the result in the destination range"13. "copy_if only copies the elements for which the predicate pred returns true"14.std::accumulate"Computes the sum of the given value init and all elements of the target range"15, or uses the operationopthat the caller gives15. - Rust. The iterator methods
map,filterandfold.map"Takes a closure and creates an iterator which calls that closure on each element."16fold"Folds every element into an accumulator by applying an operation, returning the final result."16 - Go. A
forloop with arangeclause. It "iterates through all entries of an array, slice, string or map"17. A program can write generic helper functions for map, filter and reduce. - C. A
forloop over an array. A helper function can take a function pointer for the operation. See Function pointers and delegates. - Bash. A
forloop over words. The loop will "execute commands once for each word in the resultant list, with name bound to the current word."18
from functools import reduce
nums = range(1, 7)
squares = list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, nums)))
print(*squares)
print(reduce(lambda acc, x: acc + x, squares, 0))
4 16 36
56
- Verdict: native.
mapandfilterare built-in functions, andreduceis in the modulefunctools.mapandfilterreturn iterators, solistkeeps the result for the second use.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6};
std::vector<int> evens;
std::copy_if(nums.begin(), nums.end(), std::back_inserter(evens),
[](int x) { return x % 2 == 0; });
std::vector<int> squares(evens.size());
std::transform(evens.begin(), evens.end(), squares.begin(),
[](int x) { return x * x; });
for (std::size_t i = 0; i < squares.size(); ++i) {
std::cout << (i ? " " : "") << squares[i];
}
std::cout << '\n';
std::cout << std::accumulate(squares.begin(), squares.end(), 0) << '\n';
}
4 16 36
56
- Verdict: stdlib.
std::copy_iffilters,std::transformmaps andstd::accumulatereduces. Each one works on iterators, and the caller gives the place for the output.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
List<Integer> squares = IntStream.rangeClosed(1, 6)
.filter(x -> x % 2 == 0)
.map(x -> x * x)
.boxed()
.toList();
System.out.println(squares.stream()
.map(String::valueOf)
.collect(Collectors.joining(" ")));
System.out.println(squares.stream().reduce(0, Integer::sum));
}
}
4 16 36
56
- Verdict: stdlib. The package
java.util.streamhasfilter,mapandreduce. The intermediate operations are lazy, and the terminal operationtoListorreduceruns the pipeline.
#include <stdio.h>
static int is_even(int x) { return x % 2 == 0; }
static int square(int x) { return x * x; }
static int add(int a, int b) { return a + b; }
static size_t filter(const int *in, size_t n, int (*keep)(int), int *out) {
size_t count = 0;
for (size_t i = 0; i < n; i++) {
if (keep(in[i])) {
out[count++] = in[i];
}
}
return count;
}
static void map(int *xs, size_t n, int (*f)(int)) {
for (size_t i = 0; i < n; i++) {
xs[i] = f(xs[i]);
}
}
static int reduce(const int *xs, size_t n, int init, int (*f)(int, int)) {
int acc = init;
for (size_t i = 0; i < n; i++) {
acc = f(acc, xs[i]);
}
return acc;
}
int main(void) {
int nums[] = {1, 2, 3, 4, 5, 6};
int buf[6];
size_t n = filter(nums, 6, is_even, buf);
map(buf, n, square);
for (size_t i = 0; i < n; i++) {
printf("%s%d", i ? " " : "", buf[i]);
}
printf("\n%d\n", reduce(buf, n, 0, add));
return 0;
}
4 16 36
56
- Verdict: idiom. C has no map, filter or reduce. Helper functions take a function pointer and loop over an array. The caller gives the memory for the result.
using System;
using System.Linq;
class Program
{
static void Main()
{
var squares = Enumerable.Range(1, 6)
.Where(x => x % 2 == 0)
.Select(x => x * x)
.ToList();
Console.WriteLine(string.Join(" ", squares));
Console.WriteLine(squares.Aggregate(0, (acc, x) => acc + x));
}
}
4 16 36
56
- Verdict: stdlib. LINQ calls map
Select, filterWhereand reduceAggregate.
const nums = [1, 2, 3, 4, 5, 6];
const squares = nums.filter((x) => x % 2 === 0).map((x) => x * x);
console.log(squares.join(" "));
console.log(squares.reduce((acc, x) => acc + x, 0));
4 16 36
56
- Verdict: native.
filter,mapandreduceare methods of every array. Each call tofilterormapmakes a new array.
const nums: number[] = [1, 2, 3, 4, 5, 6];
const squares: number[] = nums
.filter((x) => x % 2 === 0)
.map((x) => x * x);
console.log(squares.join(" "));
const total: number = squares.reduce((acc, x) => acc + x, 0);
console.log(total);
4 16 36
56
- Verdict: native. The array methods of JavaScript, with types. TypeScript gets the types of
xandaccfrom the array and the initial value.
package main
import (
"fmt"
"strconv"
"strings"
)
func Map[T, U any](xs []T, f func(T) U) []U {
out := make([]U, 0, len(xs))
for _, x := range xs {
out = append(out, f(x))
}
return out
}
func Filter[T any](xs []T, keep func(T) bool) []T {
var out []T
for _, x := range xs {
if keep(x) {
out = append(out, x)
}
}
return out
}
func Reduce[T, A any](xs []T, init A, f func(A, T) A) A {
acc := init
for _, x := range xs {
acc = f(acc, x)
}
return acc
}
func main() {
nums := []int{1, 2, 3, 4, 5, 6}
evens := Filter(nums, func(x int) bool { return x%2 == 0 })
squares := Map(evens, func(x int) int { return x * x })
fmt.Println(strings.Join(Map(squares, strconv.Itoa), " "))
fmt.Println(Reduce(squares, 0, func(acc, x int) int { return acc + x }))
}
4 16 36
56
- Verdict: idiom. The Go standard library has no map, filter or reduce for slices. A program writes them as generic functions with a
forloop and arangeclause.
fn main() {
let squares: Vec<i32> = (1..=6).filter(|x| x % 2 == 0).map(|x| x * x).collect();
let text: Vec<String> = squares.iter().map(|x| x.to_string()).collect();
println!("{}", text.join(" "));
println!("{}", squares.iter().fold(0, |acc, x| acc + x));
}
4 16 36
56
- Verdict: stdlib. The trait
Iteratorhasfilter,mapandfold. The adapters are lazy, andcollectruns them.
is_even() { (($1 % 2 == 0)); }
square() { echo $(($1 * $1)); }
add() { echo $(($1 + $2)); }
squares=()
for x in 1 2 3 4 5 6; do
if is_even "$x"; then
squares+=("$(square "$x")")
fi
done
echo "${squares[*]}"
total=0
for x in "${squares[@]}"; do
total=$(add "$total" "$x")
done
echo "$total"
4 16 36
56
- Verdict: idiom. Bash has no map, filter or reduce, and functions are not values. A
forloop calls a function for each word, anifkeeps the words that pass the test, and a variable holds the running total.
Variations and related ideas
- Lazy or eager. Python
mapandfilterreturn iterators4. In Java, "Intermediate operations are always lazy."10 Rustmapis lazy too: "as map() is lazy, it is best used when you’re already working with other iterators."16 JavaScript array methods make a new array at once7. - Map fusion. Two maps in a row can become one map of the composed function. "this type of optimization is known as map fusion and is the functional analog of loop fusion."1 See Function composition.
- Reduce without an initial value. JavaScript
reduceand Rustreducecan start with the first element. In JavaScript, "If initialValue is not specified, accumulator is initialized to the first value in the array"9. Rustreducereturns anOption: "If the iterator is empty, returns None"16. - MapReduce. Dean and Ghemawat named a system for large clusters after these functions. Its abstraction was inspired by the map and reduce of Lisp and "many other functional languages"19.
- Pipelines. A chain of map, filter and reduce calls is a pipeline. See Collection pipeline and Replace loop with pipeline. The task pages Map over a list and Reduce a list to a value show each step in all the languages.
Pitfalls
A Python map can be used only once
Python map and filter return iterators. "When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted"20. A second loop over the same object sees nothing:
This code runs but gives a wrong answer on purpose.
squares = map(lambda x: x * x, [1, 2, 3])
print(sum(squares))
print(sum(squares))
14
0
Call list(...) on the result when the program needs it more than once.
Reduce on an empty collection
Without an initial value, a reduce has no result for an empty collection. JavaScript reduce throws a TypeError, "Thrown if the array contains no elements and initialValue is not provided."9
This code runs but gives a wrong answer on purpose.
try {
const total = [].reduce((acc, x) => acc + x);
console.log(total);
} catch (e) {
console.log(e.name);
}
TypeError
Give the initial value: [].reduce((acc, x) => acc + x, 0) returns 0.
A lazy map that never runs
A lazy map does no work until a program reads its result. Rust says: "If you’re doing some sort of looping for a side effect, it’s considered more idiomatic to use for than map()."16 Use a for loop, or a method such as for_each, for side effects.
Cost
Each step makes one pass over the data. An eager map or filter also makes a new collection. Wikipedia says that two maps in a row are slower "because each map requires rebuilding an entire list from scratch"1. Lazy streams and iterators pass each element through all the steps and make no list in the middle1016. A loop that does all the work in one pass has the same cost as a lazy pipeline.
History
"The map function originated in functional programming languages."1 Lisp introduced a map function called maplist in 1959, "with slightly different versions already appearing in 1958."1 In 2004, Dean and Ghemawat described MapReduce, a library for computations on large clusters, and named it after the map and reduce of functional languages19.
References
- Map (higher-order function), Wikipedia, the introduction; Optimizations; Language comparison
- Filter (higher-order function), Wikipedia, the introduction; Example
- Fold (higher-order function), Wikipedia, the introduction; On lists; Evaluation order considerations
- Built-in Functions, The Python Standard Library, map; filter
- functools, The Python Standard Library, functools.reduce
- What's New In Python 3.0, Builtins
- Array.prototype.map(), MDN Web Docs, the introduction
- Array.prototype.filter(), MDN Web Docs, the introduction
- Array.prototype.reduce(), MDN Web Docs, the introduction; Parameters; Exceptions
- Package java.util.stream, Java SE 25 API, the package description; Stream operations and pipelines; Reduction operations
- Standard query operators overview, C# documentation, Query expression syntax for standard query operators
- Enumerable.Aggregate Method, .NET API, Overloads
- std::transform, C++ reference, cppreference.com, the description
- std::copy, std::copy_if, C++ reference, cppreference.com, the description
- std::accumulate, C++ reference, cppreference.com, the description
- Trait Iterator, The Rust Standard Library, map; filter; fold
- The Go Programming Language Specification, For statements with range clause
- Looping Constructs, Bash Reference Manual, for
- MapReduce, Simplified Data Processing on Large Clusters, Jeffrey Dean and Sanjay Ghemawat, OSDI 2004, 1 Introduction
- Glossary, The Python Documentation, iterator
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag BP6EDV Edit this page History Report an error Markdown