4
$\begingroup$

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.

$\endgroup$

2 Answers 2

5
$\begingroup$

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

Or Part:

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

f2[{a, b, c, d, e}]
3 a + e
$\endgroup$
3
  • $\begingroup$ @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. $\endgroup$
    – Mr.Wizard
    Commented Mar 1, 2017 at 17:33
  • $\begingroup$ @Mr.Wizard Why RuleDelayed instead of just Rule? $\endgroup$
    – Alan
    Commented Mar 1, 2017 at 19:36
  • 1
    $\begingroup$ @Alan :> will protect against the case where i is assigned a value; -> will not. $\endgroup$
    – Mr.Wizard
    Commented Mar 2, 2017 at 0:02
0
$\begingroup$

Just try this:

f[x_List]:= 3 x[[1]] + x[[5]]
$\endgroup$
1
  • 3
    $\begingroup$ 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). $\endgroup$
    – anderstood
    Commented Mar 1, 2017 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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