Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving contexts with $NewSymbol in Mathematica

I was playing around with $NewSymbol trying to find something to answer this question with. The docs say that

$NewSymbol is applied before the symbol is actually created. If the action of $NewSymbol causes the symbol to be created, perhaps in a different context, then the symbol as created will be the one used.

So I tried to automatically move a particular new symbol into a test context which should prevent its creation in the Global`* context, but the symbol gets created in both contexts.

In[1]:= Remove["Global`*"]
In[2]:= $NewSymbol=(Print[#1," : ",#2];
                    If[#1==="aLongTestSymbolName"&&#2==="Global`",
                       Symbol["TestContext`"<>#1]])&;

In[3]:= x
During evaluation of In[3]:= x : Global`
Out[3]= x

In[4]:= aLongTestSymbolName
During evaluation of In[4]:= aLongTestSymbolName : Global`
During evaluation of In[4]:= aLongTestSymbolName : TestContext`
Out[4]= aLongTestSymbolName

In[5]:= Names["Global`*"]
Out[5]= {aLongTestSymbolName,x}

In[6]:= Names["TestContext`*"]
Out[6]= {TestContext`aLongTestSymbolName}

I believe that "aLongTestSymbolName" should not be in the Global` context. Can anyone see what I've done wrong or if I've misinterpreted the documentation?


Note: Having the symbol created in both contexts is not an option for the automatic highlighting in the above linked to question. The idea is to reserve certain symbol names such as "x"~~___ for variables and "f"~~___ for functions and then use string patterns in $NewSymbol to move the symbols to the appropriate highlighted context.

like image 586
Simon Avatar asked May 29 '11 11:05

Simon


1 Answers

That is because you passed the symbol name to Print, which immediately made the symbol in Global`. :-)

Or not. I should really try things before answering, but I thought I knew this one. Oops.


It seems to me now that $NewSymbol does not intercept the creation of a symbol, or if it does, how to make use of that is not clear.

If one uses:

$NewSymbol = Print["Name: ", #2, #] &;

then:

In[10]:= aNewSymbol

During evaluation of In[10]:= Name: Global`aNewSymbol

Out[10]= aNewSymbol

We see that $NewSymbol does not work like $PrePrint in that its output does not become the expression.

Therefore, if we use:

$NewSymbol = Symbol["TestContext`" <> #] &;

aSecondSymbol

aSecondSymbol is merrily created in Global` as though nothing had changed.

If $NewSymbol can be used to direct the context in which the symbol is created, as the documentation states, it is not clear to me how this may be done.

like image 51
Mr.Wizard Avatar answered Sep 29 '22 02:09

Mr.Wizard