Background:
In OO-System t开发者_C百科he format for
object.method[var]
is
object@method[var]
basically dot becomes alpha.
I am generating ( XML back to ) code.
Question:
In[22]:= a /. a -> b
Out[22]= b
works as expected.
Now I want to change
a
into
a@new[b]
which has the following ( unwanted ) result ( since @ is reserved in Mathematica )
In[23]:= a /. a -> a@new[b]
Out[23]= a[new[b]]
although
In[25]:= a /. a -> "a@new[b]]"
Out[25]= "a@new[b]]"
seems to do the trick, now b remains unevaluated and the expression as such is not evaluated either.
How to 'escape' @ in this case ?
You should realize that the @
is a shortcut for the single square brackets (more precisely, a prefix form of building an expression), so for all practical purposes a@x
is equivalent to a[x]
, as soon as the string of code is parsed by mma parser (and I suspect that at this moment, the information about how the expression was entered - as a@x
,a[x]
or x//a
, is irreversably lost). The only way to make things work differently would be to write a pre-processor, or use something like the Notation package. However, this is not what was done in OO-System. A quick look at its implementation reveals:
(*** Invocation of Class Mathods ***)
xc_Class @ yo1_ := objectallg[xc] @ Hold[yo1];
(*** Invocation of Instance Methods ***)
xo_MathObject @ yo1_ := objectallg[xo] @ Hold[yo1];
So, what you get is perhaps a notational inconvenience, but the code should work no matter how you enter it - as a@new[b]
or as a[new[b]]]
. If you want to convert the latter to the former for presentation purposes, then the only way I see is to write your own mma parser/postprocessor to convert some a[x]
to a@x
but not others. This will not be easy though, since it should know which part to convert and which not. And I would not use string conversion in the manner you outlined - you'd need something like calls to ToExpression
to make it evaluate. etc.
So, the bottom line: you encountered a case of notational but not semantic difference, which was chosen as an easy way to introduce a convenient notation by the author of OO-System. The approach is legitimate, but you should keep in mind that it gives you just syntactic sugar on top of mma parser which is out of your direct control, and automatic conversion of a@x
to a[x]
is just one manifestation of things that may happen. You can either live with that, or use different more robust notation, such as overloaded via UpValues
Dot
function, which is another popular choice for mma OO extensions.
精彩评论