Usually, when one defines a function that's not too complex (usually a one-liner) it is customary (here we mean Mathematica custom) to define it directly without any scoping constructs (Module
, With
or Block
). For example:
myFunction[x_]:= 2 Sin[x] + Exp[-x^2]
But as the function definition gets more complex, instead of polluting the Global
context with temporary variables, we use one of the scoping constructs mentioned above.
myModuleFunction[x_Integer]:=
Module[{pts, cvx},
pts = RandomReal[4, {x, 3}];
cvx = ConvexHullMesh @ pts;
HighlightMesh[cvx, {Style[1, Black], Style[2, Yellow]}]
]
But sometimes a non-customary way is to use CompoundExpression
s like the following shows:
myCompoundFunction[x_Integer]:=
(pts = RandomReal[4, {x, 3}];
cvx = ConvexHullMesh @ pts;
HighlightMesh[cvx, {Style[1, Black], Style[2, Yellow]}]
)
Of course, in this scenario, both pts
and cvx
are now Global
variables, so if you need to use them for further calculations outside the function's scope, they're available to you whereas, in the Module
case above they aren't because we made them local. You can make those variables global using Module
and this is where we answer your question:
myModuleFunctionGlobal[x_Integer]:=
Module[{},
pts = RandomReal[4, {x, 3}];
cvx = ConvexHullMesh @ pts;
HighlightMesh[cvx, {Style[1, Black], Style[2, Yellow]}]
]
By not putting symbols defined in the body of Module
into the module list, the symbols become global variables. Your function as defined doesn't really need a Module
as it's just a simple If
statement.