How can one convert a Mathematica expression into a string without the expression being evaluated first? I tried using Hold, but it returns Hold[expr], instead of expr. Is there any way to get just the expression?
For example, I have a variable var = 5, and I need to assign the name of var to another variable, so that var2 = "var". How can I do this?
My actual use case is this:
I am trying to synchronize my mathematica variables with certain fields in an external database. Every time the external database is updated, I call on a function that is supposed to update my corresponding Mathematica variables. It takes in a list of mappings like {var1 -> "field1", var2 -> "field2"}, and its role is to access the external database, look up the value in "field1", and assign it to var1, then look up the value in "field2" and assign it to var2. The number of variables in the mapping (and their names) can be arbitrary.
The problem is that I need those var1 and var2 variables to be passed as variable names, not values, so that I can assign them inside the function. I do the assignment using
Do[ i[[1]]->i[[2]]/.remoteData, {i,mappings} ]
where remoteData = {"field1"->"value of field 1", "field2" -> "value of field 2"}. I need i[[1]] to stand for var1, not for its value. I tried setting the attribute SetAttributes[fn,HoldAll] but that didn't help.
The result that I am looking for is var1 = "value of field 1", var 2 = "value of field 2".
Answer
It looks like I should have used HoldForm instead of Hold.
Here is my current solution that does the job:
SetAttributes[fn,HoldAll];
fn[mappings_]:= ReleaseHold[Apply[Set, HoldForm[mappings]/.remoteData, {2}]]
Comments
Post a Comment