# Define function from expression

I generate expressions such as x x + x x.

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_, x_, x_]:= x x + xx


Or even better to return a function of an array:

f[x_] := x[] x[] + x[] x[]

• 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 x + x x;


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 x + x x;

Clear[f]

f[x_Symbol] = expr;

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

(* 8 *)

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

(* 8 *)

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

(* 8 *)