Map (higher-order function)

In many programming languages, map is a higher-order function that 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. It is often called apply-to-all when considered in functional form.

The concept of a map is not limited to lists: it works for sequential containers, tree-like containers, or even abstract containers such as futures and promises.

Examples: mapping a list
Suppose we have a list of integers  and would like to calculate the square of each integer. To do this, we first define a function to  a single number (shown here in Haskell):

Afterwards we may call

which yields, demonstrating that   has gone through the entire list and applied the function   to each element.

Visual example
Below, you can see a view of each step of the mapping process for a list of integers  that we want to map into a new list   according to the function $$f(x) = x + 1$$ :



The  is provided as part of the Haskell's base prelude (i.e. "standard library") and is implemented as:

Generalization
In Haskell, the polymorphic function  is generalized to a polytypic function , which applies to any type belonging the   type class.

The type constructor of lists  can be defined as an instance of the   type class using the   function from the previous example:

Other examples of  instances include trees:

Mapping over a tree yields:

For every instance of the  type class,   is contractually obliged to obey the functor laws: where  denotes function composition in Haskell.

Among other uses, this allows defining element-wise operations for various kinds of collections.

Category-theoretic background
In category theory, a functor $$F : C \rarr D$$ consists of two maps: one that sends each object $$A$$ of the category to another object $$F A$$, and one that sends each morphism $$f : A \rarr B$$ to another morphism $$Ff : FA \rarr FB$$, which acts as a homomorphism on categories (i.e. it respects the category axioms). Interpreting the universe of data types as a category $$Type$$, with morphisms being functions, then a type constructor  that is a member of the   type class is the object part of such a functor, and   is the morphism part. The functor laws described above are precisely the category-theoretic functor axioms for this functor.

Functors can also be objects in categories, with "morphisms" called natural transformations. Given two functors $$F, G : C \rarr D$$, a natural transformation $$\eta : F \rarr G$$ consists of a collection of morphisms $$\eta_A : FA \rarr GA$$, one for each object $$A$$ of the category $$D$$, which are 'natural' in the sense that they act as a 'conversion' between the two functors, taking no account of the objects that the functors are applied to. Natural transformations correspond to functions of the form, where   is a universally quantified type variable –   knows nothing about the type which inhabits. The naturality axiom of such functions is automatically satisfied because it is a so-called free theorem, depending on the fact that it is parametrically polymorphic. For example,, which reverses a list, is a natural transformation, as is  , which flattens a tree from left to right, and even  , which sorts a list based on a provided comparison function.

Optimizations
The mathematical basis of maps allow for a number of optimizations. The composition law ensures that both lead to the same result; that is, $$\operatorname{map}(f) \circ \operatorname{map}(g) = \operatorname{map}(f \circ g)$$. However, the second form is more efficient to compute than the first form, because each  requires rebuilding an entire list from scratch. Therefore, compilers will attempt to transform the first form into the second; this type of optimization is known as map fusion and is the functional analog of loop fusion.
 * and

Map functions can be and often are defined in terms of a fold such as, which means one can do a map-fold fusion:   is equivalent to.

The implementation of map above on singly linked lists is not tail-recursive, so it may build up a lot of frames on the stack when called with a large list. Many languages alternately provide a "reverse map" function, which is equivalent to reversing a mapped list, but is tail-recursive. Here is an implementation which utilizes the fold-left function.

Since reversing a singly linked list is also tail-recursive, reverse and reverse-map can be composed to perform normal map in a tail-recursive way, though it requires performing two passes over the list.

Language comparison
The map function originated in functional programming languages.

The language Lisp introduced a map function called in 1959, with slightly different versions already appearing in 1958. This is the original definition for, mapping a function over successive rest lists:

maplist[x;f] = [null[x] -> NIL;T -> cons[f[x];maplist[cdr[x];f]]]

The function  is still available in newer Lisps like Common Lisp, though functions like   or the more generic   would be preferred.

Squaring the elements of a list using  would be written in S-expression notation like this:

Using the function, above example would be written like this:

Today mapping functions are supported (or may be defined) in many procedural, object-oriented, and multi-paradigm languages as well: In C++'s Standard Library, it is called, in C# (3.0)'s LINQ library, it is provided as an extension method called. Map is also a frequently used operation in high level languages such as ColdFusion Markup Language (CFML), Perl, Python, and Ruby; the operation is called  in all four of these languages. A  alias for   is also provided in Ruby (from Smalltalk). Common Lisp provides a family of map-like functions; the one corresponding to the behavior described here is called  (  indicating access using the CAR operation). There are also languages with syntactic constructs providing the same functionality as the map function.

Map is sometimes generalized to accept dyadic (2-argument) functions that can apply a user-supplied function to corresponding elements from two lists. Some languages use special names for this, such as map2 or zipWith. Languages using explicit variadic functions may have versions of map with variable arity to support variable-arity functions. Map with 2 or more lists encounters the issue of handling when the lists are of different lengths. Various languages differ on this. Some raise an exception. Some stop after the length of the shortest list and ignore extra items on the other lists. Some continue on to the length of the longest list, and for the lists that have already ended, pass some placeholder value to the function indicating no value.

In languages which support first-class functions and currying,  may be partially applied to lift a function that works on only one value to an element-wise equivalent that works on an entire container; for example,   is a Haskell function which squares each element of a list.