1

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.

user135626
  • 258
  • 2
  • 8

3 Answers3

2

Another option is to use = instead of :=

tt = x + y
f[x_, y_] = 2*tt
f[1, 1]

Mathematica graphics

f[x, 4]

Mathematica graphics

f[x, y]

Mathematica graphics

Nasser
  • 143,286
  • 11
  • 154
  • 359
1

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

seismatica
  • 5,101
  • 1
  • 22
  • 33
0

Try this:

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

f[1, 1]
(*4*)

f[x,y]
(*2 (x + y)*)
Basheer Algohi
  • 19,917
  • 1
  • 31
  • 78
  • 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 06 '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. – Basheer Algohi Dec 06 '14 at 20:07