In general, I'd also use Piecewise
because it's clearest.
However, to play devil's advocate, here is an example of where Piecewise
is not the best choice (at least in Mathematica version 10.0.0):
Plot[
Piecewise[{{Sin[x], {x, 0} ∈
ImplicitRegion[-1 < x < 1, {x, y}]}, {1, True}}], {x, -2, 2}]
The warning here seems to be due to the fact that Piecewise
holds all its arguments and then analyzes the conditions in a form that has not been fully evaluated. At that stage it doesn't recognize the new region functionality and spits out the warning. Fortunately, the rest of the calculation is correct, but clearly the warning is incorrect. This is most likely a bug in Plot
(and appears to have been fixed in version 10.0.1 on Mac as per Michael's comment below), and it can be circumvented by using If
because the condition in If
is not held unevaluated:
Plot[
If[{x, 0} ∈ ImplicitRegion[-1 < x < 1, {x, y}], Sin[x],
1], {x, -2, 2}]
With this you get the same plot but no warnings.
Here the difference is that If
has attribute HoldRest
whereas Piecewise
has attribute HoldAll
, which we don't want.
Assuming this bug will get fixed, the fact remains that the different Hold...
attributes of If
may in certain cases make it the more natural choice, compared to Piecewise
. If that happens, the choice would be more between If
and pattern-based alternatives. Then the decision could still depend on other details, such as whether you intend to Compile
the function.
PieceWise
,UnitStep
and friends, if you want your function to integrate well with mathematical functionality such as simplifications, etc. Otherwise use rules. TheIf
is inferior to both of those ways, in most cases. $\endgroup$Piecewise
. $\endgroup$If
orWhich
), and also it tends to be somewhat slower (not by much). But, I'd agree that this is largely a matter of taste. Philosophically, the closer you are to the core language constructs, the better, and patterns / rules are certainly closer to the core than theIf
/Which
statements, because the core of Mathematica is a term-rewriting engine. $\endgroup$If/Which
and conditional pattern methods will not be handled well by either the algebra (Solve
family) or calculus (continuous and discrete) functions. $\endgroup$