I got bitten by the following:
f[x_] := 3*x;
g[x_] := If[Log[f[x]] < 0, f[x], 0];
g[x]
Out[11]= If[Log[3 x] < 0, f[x], 0]
where I thought the call to f
in the second argument to If
would be “expanded”, i.e. replaced by its expression. Once I realized this was the root cause of my issue, I could fix it by inserting Evaluate
:
h[x_] := If[Log[f[x]] < 0, Evaluate@f[x], 0];
h[x]
Out[13]= If[Log[3 x] < 0, 3 x, 0]
However, I don't understand why f
is expanded in the first argument to If
, and not in the second. Moreover, how can I know from the documentation that this will be the case? (so that I can check other functions in the future)
Hold
- attributes here $\endgroup$ – Leonid Shifrin Mar 23 '12 at 9:45