# Defining a function using a preceding expression [duplicate]

How can I automatically define a function inside my Mathematica code using a result (expression) that preceded the point of definition.

For example:

tt = x + y
x + y

f[x_, y_] := 2*tt

f[1, 1]
2 (x + y)


doesn't give $f$ as 2($x+y$) with $x$ and $y$ being variables here. So, instead of giving f[1,1]=2(1+1)=4 it gave 2(x+y) not recognizing that $x$ and $y$ are meant to be variables.

How can I define $f$ here so that it picks up its definition from the expression of $tt$ automatically, with $x$ and $y$ as variables?

The reason I need this is that it would save me manually copying and pasting the expression x+y into the function defintion, and would make my code run automatically even when tt gives different expressions.

Another option is to use = instead of :=

tt = x + y
f[x_, y_] = 2*tt
f[1, 1] f[x, 4] f[x, y] • Great. Many thanks. – user135626 Dec 6 '14 at 20:25

f[x_, y_] := Evaluate[2*tt] would also work.

Try this:

Clear f;
f[u_, v_] := 2*tt /. {x -> u, y -> v}

f[1, 1]
(*4*)

f[x,y]
(*2 (x + y)*)

• Yes, it works. Many thanks. It is a bit inconvenient that Mathematica doesn't have a simpler way to automatically detect these as variables, don't you think? – user135626 Dec 6 '14 at 20:02
• if you look at f[x_, y_] := 2*x tt; f[2, 1] // Trace you will see that tt is not evaluated until the arguments of f is passed to the left hand side. that is the nature of functions in MMA. – Algohi Dec 6 '14 at 20:07