Map (higher-order function)

From Wikipedia, the free encyclopedia

In many programming languages, map is the name of a higher-order function that applies a given function to a sequence of elements (such as a list) and returns a sequence of results. They are examples of both catamorphisms and anamorphisms.

For example, if we define a function square as follows:

square x = x * x

Then calling (map square [1,2,3,4,5]) will return [1,4,9,16,25].

Map itself may be defined recursively as:

map f [] = []
map f (x:xs) = f x : map f xs

Contents

[edit] Language comparison

The map function is especially common in functional programming languages, but some high-level procedural languages support it as well, and in others it may be defined. Common Lisp provides a whole family of map-like functions. The one that corresponds to the behavior described here is called mapcar. In C++'s Standard Template Library, the map function is called transform.

[edit] Optimizations

The mathematical basis of maps allow for a number of optimizations. If one has map f . map g ('.' is function composition) then it is the same as the simpler map (f . g) xs; that is, \left( \text{map}\,f \right) \circ \left( \text{map}\,g \right) = \text{map}\,\left( f \circ g \right). This particular optimization eliminates an expensive second map by fusing it with the first map; thus it is a "map fusion"[1].

Map functions can and often are defined in terms of a fold such as foldr, which means one can do a "map-fold fusion": f z . map g is equivalent to foldr (f . g) z.

[edit] Haskell's Functor class

In the Haskell programming language, map is generalized to a polymorphic function called fmap using the Functor type class. For every Functor instance, fmap must be defined such that it obeys the Functor laws:

  • fmap id = id (identity)
  • fmap (f . g) = fmap f . fmap g (composition)

[edit] References

  1. ^ "Map fusion: Making Haskell 225% faster"

[edit] See also

In other languages