Functions and  Map

Math 213 - Math with Mathematica
Christopher Hanusa

Overview

In this tutorial, we learn more about functions including how to apply them to lists and how to define them.

Command Basics

Structure

Mathematica has a large number of predefined functions that all have the same structure.  
Every function starts with a capital letter.  
Every function uses square brackets to include zero or more inputs.

Remember the Length function, which takes as an input a list and outputs the number of entries in the list:

Length[{1,2,3,4}]

Help with Predefined Functions

If you need help with a function, use the ? operator to pop-up a short informative blurb in the worksheet.

? Length

Clicking on the >> at the end goes to the documentation center entry for that function.

Hovering over a function with your mouse pointer creates a small menu that can give you the blurb information or a link directly to its Documentation Center entry.

Shorthand: @ (Prefix)

When your function takes only one input, you can use the @ symbol as a shortcut in lieu of the square brackets.

For example, we can rewrite the above code as:

Length@{1,2,3,4}

It is important to be aware of the @ symbol because it will appear in code you find online.
You do not have to use the @ symbol.  You should first work to be comfortable using functions with bracket notation and eventually you may find it useful. 
Furthermore, you CANNOT use the @ symbol when your function has multiple inputs like the Table command (Table always requires two inputs).

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 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 Pi/6, you can create the list of multiples of Pi/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}

Again, 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.

Syntax of Map

Ask for help to see the syntax:

?Map

Additional resource: Wolfram’s “An Elementary Introduction to the Wolfram Language”

More examples for understanding the Map command are available in Section 25 of Wolfram’s “An elementary introduction to the Wolfram Language”.  It presents a leisurely and in-depth tutorial for this and other concepts.  It is available here: http://www.wolfram.com/language/elementary-introduction/25-ways-to-apply-functions.html

Comprehension Questions

1. Before evaluating the following lines of code, anticipate what will be the result will be.  
     After evaluating the code, understand why the output is what it is and compare it with your expectations.

Sin@Pi

Map[Sin,Pi]

Range@Prime@10

Map[Prime,{1,2,4,8}]

Map[f,Map[g,Range[5]]]

Map[f@g,Range[5]]

2. Explain the difference in the outputs between Framed @ {x,y,z} and Framed /@ {x,y,z}.

3. Use the functions Prime, Map, and Range commands to generate a list of the 100th, 200th, ... up to 2000th prime numbers.

4. Use Map and Range to create this list:

{{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}}

5. If the list from the previous exercise is named triangle, what will be the difference between Length@triangle and Length/@triangle?

6. Use a Map command to find the sums of the entries in each list.

7. If there is some coordinate data ((x,y)-pairs) in the lists data1, data2, data3, and data4, how can you make a list of scatterplots of these datasets in one line of code?

Solutions:

Question 3.

Map[Prime,Range[100,2000,100]]

Question 4.

Map[Range,Range[10]]

Question 6.

Map[Total,triangle]

Question 7.

Map[ListPlot,{data1,data2,data3,data4}]

Challenge Questions

8. Use the Reverse function as necessary to change triangle into

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

9. Use a Table command to create a list of 10 to 100 points that lie in the range [0,100]x[0,100].  Then use the Map command to apply the function Disk to them.  Lastly, wrap this whole list in a Graphics command, and you will see your points displayed.

10. Use LetterNumber to find the sum of the numerical values of the letters in your name.  You will probably also need the command Characters.

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, captialize 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 not included 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"]

More information: Set vs. Set Delayed

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}]

Comprehension Questions

When you create a function, make sure to test it to see if it gives you the output you expect.

11. What do the following functions do?

f1[x_]:=Length[Range[Prime[x]]]

f2[x_,y_]:={x,y}

12. Define a function that takes as input a number n and outputs the (2^n)-th prime number

13. Define a function that takes as input three variables and outputs the sum of the first and third number and divides by the second.

14. Define a function that takes as input a list and outputs the average value of the entries.  Use the function Total.

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

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

17. What is wrong with the following code?  
      It is supposed to take in a number, divide by two, then give the floor of that number.
      For example, the output for an input of 19 should be Floor[19/2]=Floor[9.5]=9.

fountainOfYouth[x]:=Floor[x/2]
fountainOfYouth(19)

Solutions  (Do not peek until you have worked on a question for 5 minutes and asked your neighbors!)

Question 12.

f12[x_]:=Prime[2^x]

Question 13.

f13[a_,b_,c_]:=(a+c)/b

Question 14.

f14[list_]:=Total[list]/Length[list]

Question 15.

f15[n_]:=n+RandomInteger[{-5,5}]

Question 16.

ListPlot@Map[f15,Range[100]]

Question 17.

Missing the underscore, and functions always use square brackets, not parentheses.

Challenge Questions

18. Create a function that takes as input a list of numbers, interprets the list as a sequence of two-dimensional points (coordinate pairs), and outputs a scatterplot of these points.  You may find the function Partition helpful.

19. Create a function that takes as input a number n and gives as output an image with of n random points in the range [0,100]x[0,100].  (Similar to #9 above.)

20. Create a function that takes as input a string and finds the sum of the numerical values of the letters in the string.  (Similar to #10 above.)  Then use WordData and Histogram to find the distribution of these sums over words in the English Language.