# Define function from expression

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]]

• 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] – Daniel W Oct 23 '17 at 19:19

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

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 *)