Given a function with the attribute HoldFirst
, HoldAll
or similar, and a variable, list
, how can I pass the variable's name to the function without the variable being evaluated prematurely? So it is "list"
that is to be passed to the function (e.g. AppendTo
) instead of list
.
The following method fails, as AppendTo
holds the evaluation of Symbol @ "list"
, and since Symbol[...]
is not a valid variable for which a value can be assigned, an error message appears:
list = {1, 2, 3};
AppendTo[Symbol @ "list", 1];
list
Set::write: Tag Symbol in Symbol[list] is Protected.>> {1, 2, 3}
I should mention, that for certain reasons the obvious direct assignment below is not possible, as I must pass the list
as a string:
list = {1, 2, 3};
list = Append[list, 2]; (* this works, but is not what I am looking for *)
{1, 2, 3, 2}
The next approach also fails, as it issues an error message while returning the correct result:
list = {1, 2, 3};
held = AppendTo[Evaluate @ ToExpression["list", InputForm, Hold], 3];
ReleaseHold @ held;
list
AppendTo::rvalue: Hold[list] is not a variable with a value, so its value cannot be changed.>> {1, 2, 3, 3}
The final approach reveals that ReleaseHold
removes the outermost Hold
, but leaves the innermost intact.
list = {1, 2, 3};
held = Hold @ AppendTo[Evaluate@ToExpression["list", InputForm, Hold], 4];
ReleaseHold @ held
AppendTo::rvalue: Hold[list] is not a variable with a value, so its value cannot be changed.>> AppendTo[Hold[list], 4]