11.6. The map function

The map function allows to apply a function to all arguments of an ordered collection. The result is always a list even if the ordered collection is a string. If the function takes more than one argument, as many collections as arguments have to be specified as arguments. map takes the first argument from the first collection, the second one from the second collection and so on.

>>> map(isAminoAcid, "atgahryuox") 
[True, True, True, True, True, True, True, False, False, True]

>>> def add10(n):
...     return n+10
... 
>>> map(add10, [0,1,2,3,4,5])
[10, 11, 12, 13, 14, 15]
>>> def add(a,b):
        return a+b
>>> map(add, [1,2,3], [1,2,3])
[2, 4, 6]
    

Passing functions as arguments.  This is the first example where we pass a function as an argument. Even if this looks strange at the beginning, function names are references as variable names which are bound to the sequences of statements defined in the body of the function definition. The sequence of statements can be viewed as an object which has the particularity that it can be called with arguments. Figure 11.4 shows what happens when passing a function as argument. This illustrates that there is no difference between variables and functions as arguments.

Figure 11.4. Passing functions as arguments

Another example that handles function names as references is renaming a function as follows:

>>> isAA = isAminoAcid
>>> isAA('a')
True
      
The only difference between function and variable names is that function names are bound to objects that can be called using the function call syntax.
>>> isAminoAcid
<function isAminoAcid at 0x111ad0>
>>> isAminoAcid('a')
True
      
Without the parenthesis the object bound to the name isAminoAcid is shown by the interpreter, whereas adding the parentheses will call the function object bound to isAminoAcid.

Rewriting map with for map with a function that takes only one argument, can be rewritten as follows..

Rewrite map(func, collection)

  1. res < empty list
  2. for each element in collection:
    1. res <- res appended with func(element)
  3. return res