15. Module

Math 250 - Mathematical Computing
Christopher Hanusa

When you are creating more complicated functions, you will need to use the Module function.

?Module

As you can see in the explanation of Module, it helps to quarantine the variables that you only use in this function.  This type of variables are called local variables.  As you can see in the following computation, even if i is defined outside the Module, you can use i inside without worrying about contamination.  It is good practice to define your functions in such a way that any variables you only use in your function are defined as local variables.

i=10;
Print["Outside Module, i is ",i]
Module[{i=20},Print["Inside Module, i is ",i]]
Print["Outside Module, i is ",i]

More importantly, Module lets you define a function that runs multiple lines of code in a row instead of just one line of code.  Each of these intermediate lines of code must end with a semicolon so that the each line of code is computed independently.  The output from the last line of code is the output of the whole Module command.

Here is an example that takes in two inputs, multiplies them together, then checks to see if this product is even or odd.  If the product is even, it divides by two.  If the product is odd, it subtracts one and then divides by two.  Then it checks to see if this result is prime or not, and displays either “Yay!” or “Bzzzz!”.  The output of this function is the list of the first result, second result, and third result.

manySteps[{x_,y_}]:=
 Module[{first,second,third},
first=x*y;
second=If[EvenQ[first],first/2,(first-1)/2];
third=If[PrimeQ[second],"Yay!","Bzzzz!"];
{first,second,third}]

Here are some examples of the results of this function, which you can check:

manySteps[{2,5}]

manySteps[{3,5}]

manySteps[{7,6}]

When you are creating complicated functions that involve dynamic variables, use  DynamicModule instead.

?DynamicModule