# How to symbolically evaluate expression within If[]?

I have a function, say f, that needs to take one of two symbolic forms depending on the value of its inputs. This function is part of a very large expression, and I'd like to evaluate the entire superexpression symbolically (in order to write it to a .m file for future numeric evaluation).

I find that since my function contains an If[] statement, I cannot get it to evaluate the arguments of If[] symbolically. As a minimal example, take

f[x1] = a;
f[x2] = b;
g[y_] := If[y > 0, f[x1], f[x2]];


I find that g[y] evaluates to If[y > 0, f[x1], f[x2]], but I would like it to evaluate to If[y > 0, a, b]. How can I make this happen?

I would suggest to use Piecewise instead, which is designed for functions that take different values depending on some condition (it also plays nicer with a large part of the symbolic functionality of Mathematica).

You can either use PiecewiseExpand to convert the If:

f[x1] = a;
f[x2] = b;
g[y_] := If[y > 0, f[x1], f[x2]];

PiecewiseExpand@g[y]
(* Piecewise[{{a, y > 0}}, b] *)


Or redefine g directly:

g[y_] := Piecewise[{{f[x1], y > 0}}, f[x2]]

g[y]
(* Piecewise[{{a, y > 0}}, b] *)

• Or use an immediate assignment: g[y_] = Piecewise[{{f[x1], y > 0}}, f[x2]] to evaluate the subexpressions as desired at definition-time instead of at use-time. Jul 9, 2021 at 17:28

It turns out that one solution is to use the Evaluate[] function, as in the following:

f[x1] = a;
f[x2] = b;
g[y_] := If[y > 0, Evaluate[f[x1]], Evaluate[f[x2]]];


This achieves the desired outcome.