One can do
expression = a + 1;
f[a_] := Evaluate[expression]
but how would one do something like this
expression = a + 1;
g[x_] := Module[{a,b},
a=1;
b=Evaluate[expression];
x*b
]
so that only variable b right-hand side would be evaluated and not the whole Module. This would be useful for using long formulas generated by mathematica in own function definitions.
The solution suitable for me:
Thanks Jens for the answer, that pointed me to the right direction. The solution I was looking for and works for me is
expression = a + 1;
With[{expr=expression},
f[x_]:=Block[{a,b},
a = 1;
b = expr;
x*b
]
]
So using With outside of SetDelayed causes evaluation of expression as desired (Jens answer) and the naming problem (a and $a) is solved by using Block instead of Module.
Comments
Post a Comment