I often find it useful to define a symbol from strings (often in a loop in which I define other symbols). This I accomplish with Symbol
(and often ToString
).
However, if the symbol has already been defined, my call to Symbol
returns not the symbol, but that to which the symbol evaluates.
This may arise rarely, but I stumbled upon it when automatically generating usage
messages, as in the following example.
vars = {x,y};
x$dN = {x1, x2};
y$dN = {y1, y2};
For[ i = 1, i <= Length[vars], i++,
Evaluate[
Symbol[
ToString[vars[[i]]] <> "$dN"
]
]::usage
=
"generic (no argument) thermodynamic quantity vector"
]
(* Symbol::symname: The string "{x1, x2}$dN" cannot be used for a symbol name.
A symbol name must start with a letter followed by letters and numbers" *)
This is the obvious error because I'm trying to define the usage
for x$dN
, which evaluates to x$dN = {x1, x2}
.
So my question is: can we sometimes leave a symbol unevaluated, yet use it as a symbol?
ReleaseHold@Hold[MessageName][ToExpression["symb", InputForm, Hold], "usage"]
. UsingToExpression
with a third argument is key here. $\endgroup$