4
$\begingroup$

I generate expressions such as x[1] x[2] + x[2] x[3].

How can I can turn these expressions to functions?

My current code simply returns the above expression and then I use different values for x[i]'s to evaluate it. It would be much better if I could return a function of x[i]'s instead, for example:

f[x[1]_, x[2]_, x[3]_]:= x[1] x[2] + x[2]x[3]

Or even better to return a function of an array:

f[x_] := x[[1]] x[[2]] + x[[2]] x[[3]]
$\endgroup$
  • $\begingroup$ My first impulse was to do as Carl Woll suggests below, but the second part of your question makes me wonder if you are looking for: f[x_] := Indexed[x, 1] Indexed[x, 2] + Indexed[x, 2] Indexed[x, 3] $\endgroup$ – Daniel W Oct 23 '17 at 19:19
6
$\begingroup$

Let:

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

Then, you can use With to inject expr as follows:

With[{e = expr}, f[z_] := Block[{x}, x[i_]:=z[[i]]; e]]

Example:

f[{a,b,c}]

a b + b c

|improve this answer|||||
$\endgroup$
5
$\begingroup$
expr = x[1] x[2] + x[2] x[3];

Clear[f]

f[x_Symbol] = expr;

f[x] /. {x[1] -> 1, x[2] -> 2, x[3] -> 3}

(* 8 *)

f[y] /. {y[1] -> 1, y[2] -> 2, y[3] -> 3}

(* 8 *)

z[1] = 1; z[2] = 2; z[3] = 3; f[z]

(* 8 *)
|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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