此为 Mathematica 7 文档,内容基于更早版本的 Wolfram 语言
查看最新文档(版本11.1)
Mathematica HowTo
How to | Map a Function over a List
Mathematica includes many powerful operations for working with lists. It is often desirable to map a function onto each individual element in a list. While listable functions do this by default, you can use Map to do this with nonlistable functions.
First set up a list of the integers from 1 to 5:
In[1]:=
Click for copyable input
Out[1]=
You can map a function over every element of the list using Map; this example uses an undefined function f:
In[2]:=
Click for copyable input
Out[2]=
You can use /@ as a shorthand for Map (this is the same command as in the previous example):
In[3]:=
Click for copyable input
Out[3]=
Most mathematical functions have the Listable property, meaning they automatically map over lists:
In[4]:=
Click for copyable input
Out[4]=
In[5]:=
Click for copyable input
Out[5]=
If the function is not Listable, you can use Map, instead. Set up a list of five 2×2 matrices:
In[6]:=
Click for copyable input
Out[6]=
Use Map to map MatrixForm over the list to see each of them in mathematical notation:
In[7]:=
Click for copyable input
Out[7]=
Now use Map to calculate the eigenvalues of each of the matrices in the list:
In[8]:=
Click for copyable input
Out[8]=
Map does not just operate on lists. It can be used for any expression:
In[9]:=
Click for copyable input
Out[9]=
    
Apply is another functional programming operation. It replaces the head of an expression.
You can see how this works using two undefined functions, f and g:
In[10]:=
Click for copyable input
Out[10]=
Apply has @@ for a shorthand notation (this is the same command as the previous example):
In[11]:=
Click for copyable input
Out[11]=
Common expressions are shown in StandardForm in Mathematica, but their underlying FullForm shows how Apply can be used:
In[12]:=
Click for copyable input
Out[12]=
For example, this changes a sum into a product:
In[13]:=
Click for copyable input
Out[13]=
    
Apply is useful when you want to turn the elements in a list into function arguments.
Create a list of five ordered pairs {a, b}:
In[14]:=
Click for copyable input
Out[14]=
Mod finds the remainder when dividing the first number of an ordered pair by the second:
In[15]:=
Click for copyable input
Out[15]=
To apply Mod to all of the pairs, you need to work at level 1 of the list (specified by the {1}):
In[16]:=
Click for copyable input
Out[16]=
You can use @@@ as a shorthand to apply at level 1:
In[17]:=
Click for copyable input
Out[17]=
This is another way to do the same thing using a pure function with Function:
In[18]:=
Click for copyable input
Out[18]=
This uses the short form of Function:
In[19]:=
Click for copyable input
Out[19]=