Elegantly change the list of variables: AddTo generalization, TimesBy, etc.

Suppose I defined a list of variables

{a,b,c} = {1,2,3}

If I want to double them, I can do this:

{a,b,c} *= 2

Now the variables {a, b, c} are evaluated to {2,4,6}. If I want to apply an arbitrary transform function to them, I can do this:

{a,b,c} = f /@ {a,b,c}

How would you do this without specifying a list of variables twice?

(Set aside the objection that I will probably need for the array, not a list of explicitly named variables.)

+3
source share
2 answers

You can do it:

Function[Null, # = f /@ #, HoldAll][{a, b, c}]

For instance,

In[1]:= 
{a,b,c}={1,2,3};
Function[Null, #=f/@#,HoldAll][{a,b,c}];
{a,b,c}

Out[3]= {f[1],f[2],f[3]}

f, set. foreach , Listable:

ClearAll[set];
SetAttributes[set, {HoldFirst, Listable}]
set[var_, f_] := var = f[var];

:

In[10]:= {a,b,c}={1,2,3};
set[{a,b,c},f1];
{a,b,c}

Out[12]= {f1[1],f1[2],f1[3]}

, f Listable, , M8 Compile Listabe , , . , set ( , , f Listable) Listable set.

+2

, : ForEach Mathematica

each, , :

each[i_, {a,b,c}, i = f[i]]
0

Source: https://habr.com/ru/post/1785858/


All Articles