此为 Mathematica 4 文档,内容基于更早版本的 Wolfram 语言
查看最新文档(版本11.2)

Module

Usage

Module[ x, y, ...  , expr] 指定expr中符号x, y, ...出现的位置应被当作局部值.
Module[ x =  , ...  , expr] 用来定义 x, ... 的初始值.


Notes

Module允许你创建局部变量,该局部变量的名称相对于模块是局部的.
• 在每次被调用时,Module创建新的符号来表示它的每个局部变量.
Module 创建名称为 xxx$nnn 的符号来表示名称为 xxx 的局部变量. nnn$ModuleNumber当前的值.
• 每次任何模块被使用时,$ModuleNumber的值都会增加.
• 在计算expr之前,Module使用新符号来替换出现在 expr 中任意位置除作为scoping结构中的局部变量外的每一个局部变量.
• 使用Module 创建的符号具有Temporary属性.
• 使用Module 创建的符号可以从模块返回.
• 你使用Module[ vars , body /; cond]作为带有一个条件的变换法则的右式.
Module 具有HoldAll属性.
Module 是一个scoping结构 (参见A.3.8节).
Module 结构可以以任何方式嵌套.
Module 实现词汇scoping.
• 参见 Mathematica 全书: 1.7.2节2.6.1节.
• 同时参见: With, Block, Unique.
Further Examples

This defines the global variable t to have the value 17.

In[1]:=  

Out[1]=

The t inside the Module is local, so it can be treated independently of the global t.

In[2]:=  

Out[2]=

The global t still has value 17.

In[3]:=  

Out[3]=

The most common way that modules are used is to set up temporary or intermediate variables inside functions you define. It is important to make sure that such variables are kept local. If they are not, then you will run into trouble whenever their names happen to coincide with the names of other variables.

The intermediate variable t is specified to be local to the module.

In[4]:=  

This runs the function t.

In[5]:=  

Out[5]=

The global t still has value 17.

In[6]:=  

Out[6]=

You can treat local variables in modules just like other symbols. Thus, for example, you can us them as names for local functions, you can assign attributes to them and so on.

This sets up a module which defines a local function f.

In[7]:=  

In this case, the local function f is just an ordinary factorial.

In[8]:=  

Out[8]=

In this case, f is set up as a generalized factorial.

In[9]:=  

Out[9]=

When you set up a local variable in a module, Mathematica initially assigns no value to the variable. This means that you can use the variable in a purely symbolic way, even if there was a global value defined for the variable outside the module.

This uses the global value of t defined above, and so yields a number.

In[10]:=  

Out[10]=

Here, Length simply receives a number as its argument.

In[11]:=  

Out[11]=

The local variable t has no value, so it acts as a symbol, and Expand produces the anticipated algebraic result.

In[12]:=  

Out[12]=