This question already has an answer here:

I have a large number of data variables that are represented in MMA as symbols set to lists. For example:

x = {1, 2, 3};
y = {4, 5, 6};

I want to be able to write simple transformation rules on the data that I'd like to apply to the variables without writing the code out for each variable. For example, instead of

x = f[x];
y = f[y];

I'd like to write:

 vars = {x, y};
 (# = f[#])& /@ vars;

Or, if vars was defined too late (and x and y are already set to the actual data lists) then:

(# = f[#])& /@ {x, y};

Of course neither of these approaches work because x,y are evaluated. I've tried various combinations of Hold applied to the variable list vars but have been unable to get anything to work. Is something like this even possible? Or, is there a MMA way of doing this?


marked as duplicate by J. M. will be back soon Jun 15 '13 at 2:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    $\begingroup$ Take a look at Attributes. In particular HoldFirst $\endgroup$ – Dr. belisarius Jun 14 '13 at 21:50
  • $\begingroup$ To adapt the solution in the other thread to your situation: Scan[Function[p, p = f /@ p, HoldAll], Hold[x, y]] $\endgroup$ – J. M. will be back soon Jun 15 '13 at 2:53
  • $\begingroup$ The answers to the referenced duplicate are brilliant, many thanks to 0x4A4D. $\endgroup$ – pjc42 Jun 15 '13 at 17:17

Following belisarius comment you could do something like

Function[z, z = f /@ z, HoldFirst]@{x, y}

So you put the Map operation inside the pure function. E.g.

x = {1, 2, 3};
y = {4, 5, 6};
f = #1 + 1 &;
Function[z, z = f /@ z, HoldFirst][{x, y}];

seems to work.

  • $\begingroup$ Thanks, had not seen attributes applied to pure functions before. This may be my answer but before closing I wanted to ask if there is a way to use my definition of vars, i.e. Function[z, z = f /@ z, HoldFirst][vars]; This is the most convenient way and where all this started for me. Thanks. $\endgroup$ – pjc42 Jun 14 '13 at 23:50
  • $\begingroup$ The question on using vars is answered the referred duplicate above. $\endgroup$ – pjc42 Jun 15 '13 at 17:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.