1
$\begingroup$

I have a Module which has $n$ local variables, say $a_i$. Now I want to write my Module in such a way that I do not need to change the code for varying $n$.

My approach is

localVar=Table[Subscript[a, i], {i, 0, n}];
MyModule[arguments_] := Module[localVar,...

However, Mathematica interprets localVar as a local Variable, rather than the list which I have defined before.

Is there a way to tell it to take the localVar inside Module as the thing I defined before?

$\endgroup$
6
  • $\begingroup$ You can't really have same variable being global and also local at same time. You need to decide. You could do something like this !Mathematica graphics but this is all bad coding. Better to pass as argument all the input that needs to be used by the function. Function should not access global anything. It should be pure function (pure in the sense of functional programming thing) $\endgroup$
    – Nasser
    Commented Jan 12 at 9:47
  • $\begingroup$ Note: I realized how the Def of localVar does not work anyways. As a workaround, I used: Table[ToExpression["a" <> ToString@i], {i, 0, l}]. But the same problem still persists $\endgroup$ Commented Jan 12 at 9:47
  • $\begingroup$ @Nasser The way you do it, I think that I still only have one local Variable, which is mylocalVar, a list of 3 elements, in your example. I want to have a variable amount of local variables. I.e. without changing the code for myModule, I want it to have, say, 4 variables or 3, depending on which list I give it. $\endgroup$ Commented Jan 12 at 9:50
  • 1
    $\begingroup$ You can do Module[Evaluate[localVar], ...] . And like you noticed: you can't have Subscript or anything like that as local variables. It has to be a list of symbols. $\endgroup$ Commented Jan 12 at 10:18
  • $\begingroup$ @SjoerdSmit If you put it as an answer, I can accept it. Thanks! $\endgroup$ Commented Jan 12 at 10:36

1 Answer 1

5
$\begingroup$

Module has the HoldAll attribute, so if you want to evaluate localVar to the list of symbols, you either have to use Evaluate or With:

Module[Evaluate[localVar], ...]

or

With[{localVar = Table[ToExpression["a" <> ToString @ i], {i, 0, l}]},
    Module[localVar, ...]
]

An even better way to do it, is by using ResourceFunction["ConvertStringsToSymbols"]

With[{localVar = "a" <> ToString[#] & /@ Range[10]}, 
 ResourceFunction["ConvertStringsToSymbols"][
  Module[localVar, ...],
  localVar
  ]
]

The reason this is better, is because this function also works if one of the ai variables already has a value. The other methods will fail in that case.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.