I have a massive amount of code with lots of Table
and Sum
inside a Module
. Each with their own iterators, and I have completely lost track of all of them. But if the user calls the function with an argument matching the name of the iterator, the code no long works as intended.
An example is this function that is supposed to return a list of three repeated symbols:
function[x_] :=
Module[{},
answer = Table[x, {i, 1, 3}];
Return[answer];
]
For example:
function[a]
(*{a,a,a}*)
But this can be broken by
function[i]
(*{1,2,3}*)
Obviously, Table
is confusing the input x=i
with its own iterator i
. What is the fool-proof fix for this? Is there a solution without:
Finding the names of all the iterators and listing them all as private variables inside
Module
?Finding all the iterators and renaming them
longAndComplicated1
,longAndComplicated2
, etc.?
Answer
Make use of Module
's capability to localize variables.
f[x_] := Module[{i}, Table[x, {i, 1, 3}]]
f[i]
{i, i, i}
Also, with i
localized, you don't need to use distinct iterator names in different iteration constructs.
g[x_] :=
Module[{i, a, b},
a = Table[x, {i, 3}];
b = Table[x^3, {i, 2}];
{a, b}]
{g[i], g[a], g[b]}
{{{i, i, i}, {i^3, i^3}},
{{a, a, a}, {a^3, a^3}},
{{b, b, b}, {b^3, b^3}}
Further, note that you don't need to use Return
if you use the semicolon ( ; ) operator properly. (Yes, semicolon is an operator in Mathematica, not a terminator.) See this answer for more information on the semicolon operator. Actually, it likely you will benefit from all answers given on the page I have linked to.
Comments
Post a Comment