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$
1
  • $\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
    Commented Oct 23, 2017 at 19:19

2 Answers 2

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

$\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 *)
$\endgroup$

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.