I need to use local indexed variables inside With
but it is not allowed, the same for Block
and Module
. The following codes return an error.
What can be done in this case since I already have large expressions with indexed variables.
With[{a[1] = 7}, Print[a[1]]]
Block[{a[1] = 7}, Print[a[1]]]
Module[{a[1] = 7}, Print[a[1]]]
"Local variable specification {a[1]=7} contains a[1]=7, which is an assignment to a[1]; only assignments to symbols are allowed."
On one hand they recommend not to use code like ToExpression["a" <> "1"]
which produces variable a1
but instead it is advised to use indexed variable a[1]
.
On the other hand when you did it that way you find out that they are useless with With
.
Module[{a}, a[1] = 7; Print[a[1]]]
? $\endgroup$ToExpression["a"<>"1"]
strategy when you're wanting to "localize" variables inModule
,Block
, orWith
anyway. I don't think "isn't it ridiculous?" is a legitimate question for this forum. I could come up with several ways to create some sort of indexing within these structures, but there isn't nearly enough information here for me to provide clear explanations or guidance. $\endgroup$Subscript
.Subscript
is really a formatting utility and doesn't really lend itself to the use of just "subscripted variable" like people want it to be--like one could write on a chalkboard in math class. $\endgroup$a1
,a2
,a3
..., is a code smell. You can't say it's always bad programming, but it's bad often enough that you should be suspicious. 99% of the time, the semantic that is desired can be better represented byIndexed
,Part
, or down-values, or something else entirely. $\endgroup$