variable definitions - Subscripts - Why do I see the error "only assignments to symbols are allowed" when using a Module and not otherwise?
When I type
Remove["Global`*"]
foo[] := Module[{Subscript[a, 1] = "x"}, 0];
foo[]
I get the expected error "only assignments to symbols are allowed". I understand the error.
But why I do not get the same error when I type the same assignment in the notebook?
Remove["Global`*"]
Subscript[a, 1] = "x"
No error and no beep.
What is the difference? I'm using version 8.04 on Windows.
Update
The non-localized trick shown by Szabolcs answer worked for me on a demo. Here is a screen shot of the result. What I was trying to do is to typeset some information about a solver, some matrix equation, and I thought why not take advantage of MatrixForm
and Grid
's nice way of typesetting things, and display the information right there in the demo screen as an option? This is easier than putting it in the text section below where it can hard to get to as I have so many such things.
Here is an example of the code and the result. You can see I did not localized these symbols in the module which builds this expression. I just started trying this idea, but so far I am happy that it worked. This below is only an example, not cleaned up, just wanted to see if the demo will work.
Answer
This is because only symbols can be localized by Module
. It is not about assignment, but localization.
Subscript[a, 1]
is not a symbol, but a compound expression, so:
Module[{Subscript[a, 1] = "x"}, 0] (* <-- not allowed *)
Module[{}, Subscript[a, 1] = "x"] (* <-- allowed but not localized *)
I agree that the error you got may be a bit confusing.
A somewhat ugly workaround is Module[{Subscript}, Subscript[a, 1] = "x"]
or you may try to use the Notation`
package to create symbol names with subscripts in them. A word of warning though: in some cases, Module
variables that have DownValue
s do not get destroyed when the Module
finishes evaluating. For more information, see the end of the Module section in this answer by Leonid Shifrin, and the comments on that answer.
Comments
Post a Comment