# Define function of a list from a function of its elements (Set)

I asked a similar question there: Define function of a list from a function of its elements (SetDelayed). This one is different because I'd like to use Set instead of SetDelayed, and it makes a big difference.

Let's say I have a long expression which depends on x[1], x[2], ..., for example here simply 3x[1]+x[5]. I want to define a function based on this expression, but of course I don't want to rewrite it manually as:

 f[{x1_,x2_,x3_,x4_,x5_}] = 3x1 + x5


Just to explain better, I'd looking for something like the incorrect

 expr = 3x[1] + x[5]
f[Array[x_]] = expr


so that f[{a,b,c,d,e}] would return 3a + e.

With Indexed:

expr = 3 x[1] + x[5];

f[x_List] = expr /. x[i_] :> Indexed[x, i];

f[{a, b, c, d, e}]

3 a + e

f2[x_List] = expr /. x[i_] :> Quiet[ x[[i]] ];

f2[{a, b, c, d, e}]

3 a + e

• @anderstood Since you want that form there is no point to the Block construct I presented first; I therefore removed the extraneous parts of my answer. – Mr.Wizard Mar 1 '17 at 17:33
• @Mr.Wizard Why RuleDelayed instead of just Rule? – Alan Mar 1 '17 at 19:36
• @Alan :> will protect against the case where i is assigned a value; -> will not. – Mr.Wizard Mar 2 '17 at 0:02

Just try this:

f[x_List]:= 3 x[[1]] + x[[5]]

• You are using SetDelayed instead of Set, and you are not using expr directly (I don't want to retype expr which I supposed to be complicated). – anderstood Mar 1 '17 at 17:10