Here is a simple example to illustrate my problem:
expr = {a + b*Exp[-r t], a - b*Exp[-r t]}
(* {a + b E^(-r t), a - b E^(-r t)} *)
g[t_, b_] := Total[Evaluate[expr], {2}]
g[10, {b1, b2}]
(* {a + b E^(-r t), a - b E^(-r t)} *)
It looks is like Total[]
undoes the Evaluate[]
statement. Indeed:
g[10, 1]
(* {a + b E^(-r t), a - b E^(-r t)} *)
What I wanted and expected was the same output as when doing
h[t_, b_] := Evaluate[expr]
Total[h[10, {b1, b2}], {2}]
(* {2 a + b1 E^(-10 r) + b2 E^(-10 r),
2 a - b1 E^(-10 r) - b2 E^(-10 r)} *)
I would like to understand why it can't be done the way I did, and how to do it instead (in the function definition). I am using Mathematica 13.3 on Windows.
expr = x; f1[x_] := expr; f2[x_] := Evaluate[expr]; f3[x_] := f4[Evaluate[expr]]; {f1[0], f2[0], f3[0]}
$\endgroup$Definition[f1]
,Definition[f2]
andDefinition[f3]
. You will see that inf2
,expr
evaluated tox
already at the time you defined the function, while in the other two cases,expr
remained intact, as expected.x
inexpr
will then not be automatically replaced with the function argumentx
! There are various solutions, for example:g[t_, bb_] := Total[expr /. b -> bb, {2}]
orClear[expr]; expr[b_] := {a + b*Exp[-r t], a - b*Exp[-r t]}; g[t_, b_] := Total[expr[b], {2}]
$\endgroup$Evaluate
, it states "Evaluate works only on the first level, directly inside a held function". This seems perfectly reasonable to me, because otherwise the evaluation process would need to parse the expression tree entirely looking for anyEvaluate
s before moving on. $\endgroup$