You must introduce some form of holding in you definition of compvar
as otherwise, assuming it is defined after var1
, var2
, etc., there is no information to retrieve:
var1 = 10;
var2 = 11;
var3 = 17;
var4 = 5;
compvar = {var1, var2, var3, var4};
Definition[compvar]
compvar = {10, 11, 17, 5}
You could use Hold
but then you would need to ReleaseHold
(or similar) every time you used compvar
. Instead I suggest you use SetDelayed
and then recover the definition using my step
function from:
It returns an expression wrapped in HoldForm
:
compvar := {var1, var2, var3, var4};
step[compvar] // InputForm
HoldForm[{var1, var2, var3, var4}]
To convert to a list of strings:
Cases[step[compvar], s_Symbol :> SymbolName @ Unevaluated @ s, {2}]
{"var1", "var2", "var3", "var4"}
Or:
StringSplit[ToString @ step[compvar], ("{" | "," | " " | "}") ..]
{"var1", "var2", "var3", "var4"}
The first method will return Symbols (as strings) only while the second will convert other expressions as well.
Incidentally if you do not need to store your Symbols in a List
you could use a more direct form:
compHeld = Hold[var1, var2, var3, var4];
List @@ SymbolName /@ Unevaluated /@ compHeld
{"var1", "var2", "var3", "var4"}
compvarstr = ToString[#] & /@ compvar
!Mathematica graphics $\endgroup${10, 11, 17, 5}
, becuase M has evaluated all those variables to their values. Only way, is not to make the assignment to the valuates, but using replacement rule. I'll post an example $\endgroup$