I have already asked a related question here why set values in this way doesn't work? But I think I have to write the question which I encountered explicitly?
tmp = {1, 2, 3, 4, 5}
label[i_, p_] := i + p
test[p_] := Table[tmp[[label[i, p]]], {i, 1, 2}]
Here I defined a function test and the thing I want to is that change the values of list tmp via setting values to function test. While simply write
test[1]={111,222}
and expecting tmp will change to {1,111,222,3,4,5} is not possible.
So how to achive this? I have tried many Hold things, but failed.
Inspired by andre. I know that Set has attribute HoldFirst. So I tried Evaluate
Evaluate[test[1]]={111,222}
this won't work! I guess the problem is that I must properly Hold label[i,p] and tmp[[]] in the table. But I can't work it out. Anyone help?
Answer
This seems rather convoluted, and there is almost certainly an easier way to approach whatever it is you are wishing to do, but I like answering questions like this as it allows working with more unusual aspects of the language.
We can do this:
Block[{tmp, Part}, Hold @@ {test[2]}] /. _[x_] :> (x = {111, 222});
As with my previous answer we may wish to wrap this into a more convenient syntax, but there is a problem; how do we know that tmp is the symbol to be blocked? We can give it explicitly, if that is acceptable.
func_[boost2[expr_, sym__], arg___] ^:=
Block[{sym, Part}, Hold @@ {expr}] /. _[x_] :> func[x, arg]
Use syntax:
boost2[test[1], tmp] = {111, 222};
I'm not certain if there is any point in keeping the generalized form of this function in analogy to the original bump function, but it was easy for me to write it this way. If you wish only to have this operation apply to Set it may be simpler to write a mySet analog, like this:
SetAttributes[mySet, {HoldAll, SequenceHold}]
mySet[expr_, sym__, value_] :=
Block[{sym}, Hold @@ {expr} // Quiet] /. _[x_] :> (x = value)
mySet[test[1], tmp, {111, 222}]
To me this syntax is not as elegant as the form above.
Comments
Post a Comment