Map (higher-order function)

This is an old revision of this page, as edited by Spoon! (talk | contribs) at 07:50, 18 August 2006. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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.

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

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.

In Common Lisp, there is a whole family of map-like functions. The one that corresponds to the behaviour described here is called mapcar.

In C++'s standard library, the map function is called transform

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 by the Functor laws:

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