Functions and the Map command

Math 250 - Mathematical Computing
Christopher Hanusa

5.1 Aim

In this tutorial, we learn how to apply functions to every element in a list and how to create our own function definitions.

5.2 Key function: Map

An extremely important function in Mathematica is  Map.  In other computer languages people use For loops to repeat the same set of rules multiple times.  In Mathematica we can often avoid using For loops entirely by using the Map command instead.

The Map command takes in two inputs: a function and a list.
Map applies the function to each entry of the list, returning the results in a new list.

For example, if you want to know the values of sin(x) for multiples of π/6, you can create the list of multiples of π/6 and then Map the Sin function onto the list:

piList=Range[0,2Pi,Pi/6]

Map[Sin,piList]

More generically, if your list is {a,b,c} and your function is f, then Map will return a list with f evaluated at each entry:

Map[f,{a,b,c}]

Shorthand: /@

Because it is used so frequently, there is a shorthand for Map that you may see “out in the wild”.  It is the pair of symbols “Slash-At”: /@

Sin/@piList

f/@{a,b,c}

As before, you do not have to use the /@ operator.  You should first work to be comfortable how Map works and eventually you may find it useful.

Examples

Example 5.2.1. Use Map and Range to define the following list as the variable triangle.

{{1},
{1,2},
{1,2,3},
{1,2,3,4},
{1,2,3,4,5},
{1,2,3,4,5,6},
{1,2,3,4,5,6,7},
{1,2,3,4,5,6,7,8},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9,10}}

Example 5.2.2. What is the difference between Length@triangle and Length/@triangle?

Example 5.2.3. Use a Map command to find the sums of the entries in each list of triangle.

5.3 Defining a named function

f[x_,y_] := RHS

(RHS stands for Right Hand Side.)

f is the coder-specified name of the function.  Since all built-in Mathematica functions start with a capital letter, it’s good practice to start user-defined functions with a lower case letter.  To use multiple-word function names, capitalize it #likeAHashtag.

All functions use square brackets [ ] to mark the beginning and end of the inputs.

Inside the square brackets, you give coder-specified names to each of the variables since you will be using them on the Right Hand Side of the definition when you code what the function does.

When you define these variables, use an underscore _ to tell Mathematica that the input for this variable can be any one thing. (One number, One list, One shape, ... anything!)  This is the simplest type of a “pattern” in Mathematica.

Unlike defining variables and using the = operator, when you define a function you use the := operator.  It is called “SetDelayed” because it means that every time you evaluate the left hand side (When you call the function), it RE-evaluates the Right Hand Side.  (See below for more information.)

Simple function example

Define a function that takes as an input a number and outputs its square.

squareMe[x_]:=x^2

squareMe[-6]

Notice that Mathematica colors the coder-defined variables in the definition teal. If you had made a mistake and forgotten to include the underscore, the color would be different:

squareMe[x]:=x^2

Simple function with more than one variable

Define a function that takes as an input two numbers and outputs its sum.

addEmUp[x_,y_]:=x+y

addEmUp[3,-10]

Notice that we did not specify that x and y had to be numbers.  Mathematica will add together whatever you put as inputs, even if the sum can’t be simplified.

addEmUp[{2,3},{9,-10}]

addEmUp[Red,Orange]

addEmUp["Hello","Goodbye"]

Examples

Example 5.3.1.  Define a function that takes as input a number and outputs that number plus a random integer between -5 and 5.

Example 5.3.2. Take the function you defined in Example 5.3.1, apply it to all the elements in the list {1,...,100}, and create a scatterplot of the result.

5.4 More information: Set vs. SetDelayed

Compare the following two lines of code:

x1=RandomInteger[{1,10}];
x2:=RandomInteger[{1,10}];

Notice that x1 is defined using Set (=) and x2 is defined using SetDelayed (:=).  This means that each time x1 is called, it will give the same random integer between 1 and 10, while each time x2 is called, it will give a new random integer between 1 and 10.

Table[x1,{10}]
Table[x2,{10}]

5.5 Nest and NestList

Another instance where computer languages often use a For loop involves applying the same function over and over to an initial input.  
In Mathematica, use the Nest command instead.  
And if you want to see the intermediate results, use the NestList command.

?Nest
?NestList

Here is an example that uses the function “subtract one”, and applies it to the input 100 four times in a row.  When you do this, you get the final answer 96, because
subtractOne[subtractOne[subtractOne[subtractOne[100]]]]=((((100-1)-1)-1)-1)=96.

subtractOne[x_]:=x-1
Nest[subtractOne,100,4]

But perhaps you wanted to know all the intermediate results.  Then use NestList to see the initial input, and the four steps.

NestList[subtractOne,100,4]

5.6 An advanced extension: MapThread

Map is used to apply a function (that takes one input) to each element in a list of objects.

When your function takes multiple inputs, and you want more than one of those inputs to vary, you need to use MapThread instead.

Syntax

Suppose your function takes in three inputs, x, y, and z:

function[x_,y_,z_]:=x^2+y^2+z^2

And you have a list of x-values, a list of y-values, and a list of z-values, ALL OF THE SAME LENGTH!

xlist=Range[10]
ylist=RandomInteger[{1,10},10]
zlist=Range[10,1,-1]

Then to evaluate the function with the first input in each list, then the second input in each list, then the third input in each list, etcetera, use MapThread.  
MapThread takes two inputs:  the first input is the function that will be applied and the second input is a list of the input lists.  (Read that again to make sure you understand what it is saying.)

Here is the continuation of the above example, in which we use MapThread to calculate f((Subscript[x, 1]),(Subscript[y, 1]),(Subscript[z, 1])) then f((Subscript[x, 2]),(Subscript[y, 2]),(Subscript[z, 2])) then f((Subscript[x, 3]),(Subscript[y, 3]),(Subscript[z, 3])) through f((Subscript[x, 10]),(Subscript[y, 10]),(Subscript[z, 10])).

MapThread[function,{xlist,ylist,zlist}]

This is equivalent to the following more complex code:

Table[function[xlist[[i]],ylist[[i]],zlist[[i]]],{i,1,Length[xlist]}]

Examples

Example 5.6.1.  Calculate Sin[0], Cos[Pi/3], Tan[2Pi/3], Cot[Pi], Sec[4Pi/3] and Csc[5Pi/3] using MapThread.

Example 5.6.2.  Create the following list of colorful days of the week.   (Hint: To add color or other font styling, use the Style function.)