1

I'm new to Mathematica, so I don't really know, how do what I want, and I don't even know how to google it.

Doing one Mathematica task for my supervisor, I faced the following problem. I need to write a function with such a syntax:

f[{{var1, val1}, {var2, val2}, ..., {varn, valn}}]

Here $var_i$ is a variable and $val_i$ is a value, which will be assigned to this variable. So this functions is a "parallel" analogue of the function Set[]. $var_i$ has already its value, and it can be evaluated (but it's not what I want).

Number of variables $n$ can vary.

Apparently, I need to set Hold attribute for $f$, but what should I do next? The first thing I've tried to do was just f[l_] := l[[All, 1] = l[[All, 2]], but it didn't worked due to some part assignment restrictions.

But if I try to extract variables like vars = l[[All, 1]] and than do vars = l[[All, 2]], it doesn't work too, because vars just become replaced with values from l[[All, 2]].

I know, I must use Hold[] and Unveluated[] somehow, but I don't know how to apply them here.

P.S. The problem I've really faced is sligtly different: I want to build function, which argument is {{var1, a1, b1, n1}, ...} and which will iterate over $var_i$ from $a_i$ to $b_i$ with step $n_i$. I try to implement "parallel" Set[] first, because of its simplicity.

P.S.S. Sorry for my English, it's not my native language.

kmingulov
  • 539
  • 2
  • 9
  • you may check this question and answers http://mathematica.stackexchange.com/questions/22376/how-to-define-a-vector-with-automatically-added-symbolic-elements-with-subscript – s.s.o Aug 28 '14 at 11:11
  • I did my best to answer this but I could not understand your actual problem. If you will please attempt to clarify that, with examples, I will try to help further. – Mr.Wizard Aug 28 '14 at 11:44
  • Possible duplicate: (40094) – Mr.Wizard Aug 28 '14 at 11:46

2 Answers2

1

For the simple case where your Symbols (variables) do not already have assignments you do not even need a new function as you may simply use Set @@@:

Set @@@ {{var1, "a"}, {var2, "b"}, {var3, "c"}};

{var1, var2, var3}
{"a", "b", "c"}

If the question is why doesn't l[[All, 1] = l[[All, 2]] work see:

(This might be considered a duplicate question.)

If the Symbols already have assignments you will need a structure that will keep them unevaluated.

For example:

new = Hold[{{var1, "x"}, {var2, "y"}, {var3, "z"}}];

Apply[Set, new, {2}] // ReleaseHold;

{var1, var2, var3}
{"x", "y", "z"}

I think you will find these Q&As relevant:

Unfortunately I don't understand your P.S. problem description so I cannot address that yet.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
0

Well, seems like I solved it myself:

f[list_] := Module[{f},
  SetAttributes[f, HoldAll];
  f[{l_, v_}] := (l = v);
  f /@ MapAt[Unevaluated, Unevaluated[list], {All, 1}];
];

I don't know, is it the best solution, but it works.

kmingulov
  • 539
  • 2
  • 9