Say after some long computation we get an expression
expr=x^2
We do not know what the value of expr
beforehand.
Now we want to turn this in a function. We can use either
f[x_]=expr
or
f[x_]:=Evaluate[expr]
as suggested in this question.
However, when we do
f[x_]=Expand[expr]
or
f[x_]:=Evaluate[Expand[expr]]
The Expand
will not have any effect.
Is there any way to make this work? Of course, we can define another function
g[x_]:=Expand[f[x]]
But is there any way to do it a bit more concisely?
Update:
If you do what suggested by Kuba in the comment, you get
In[89]:= With[{expr = expr}, f11[x_] := Expand[expr]]
In[90]:= f11[a + b]
Out[90]= x^2
In[91]:= ?? f11
Notebook$$34$907690`f11
f11[x$_]:=Expand[x^2]
f[x_] = Expand[expr]
actually works fine. It expandsexpr
and then turnsx
into a function slot. Just try it withexpr = (1 + x)^10
and then evaluatef[y]
after definingf
. Or were you expecting something different? $\endgroup$ – Sjoerd Smit Dec 4 '18 at 15:47f[a+b]==Expand[(a+b)^2]=a^2+2 a b+b^2
$\endgroup$ – ablmf Dec 4 '18 at 16:36g[x] := Expand[f[x]]
method is really the way to go here, because it makes the evaluation process easiest to follow. Any other method is just going to be confusing one way or another. $\endgroup$ – Sjoerd Smit Dec 4 '18 at 17:02