Background & Context
- If is a procedural programming structure whose evaluation branch is determined by the truth value of a specified condition. If typically takes a condition plus two additional arguments: If[cond,t,f]. Here, t and f are evaluated if the condition is True or False, respectively. If may also take three additional arguments: If[cond,t,f,u]. Here, u gives the evaluation to take place if the specified condition is neither explicitly True nor explicitly False. Finally, If may take just one additional argument: If[cond,t]. In this case, the value for f is taken to be Null.
- For efficiency, If evaluates only the relevant arguments. For example, if the condition in If[cond,t,f,u] is True, only t (and neither f nor u) will be evaluated.
- ConditionalExpression is a related symbolic construct that represents an expression only when the given condition is True. Other more flexible programming structures that generalize If include Which and Switch. Mathematical functions that evaluate depending on the values of their arguments include Boole and Piecewise. Condition is a pattern that matches only if the evaluation of a test results in True. TrueQ is a specific case of If that yields True if an expression is explicitly True, and False otherwise.
Examplesopen allclose all
Basic Examples (1)
Symbolic Transformations (1)
Define a piecewise function with both If and Round as piecewise elements:
Use PiecewiseExpand to get it into piecewise normal form:
Generalizations & Extensions (1)
If can be used as a statement:
Properties & Relations (4)
Only the branch actually taken is evaluated:
Alternatively, use several conditional definitions:
Use Which rather than a nested if-then-elseif chain:
Use PiecewiseExpand to convert If to Piecewise:
Wolfram Research (1988), If, Wolfram Language function, https://reference.wolfram.com/language/ref/If.html.
Wolfram Language. 1988. "If." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/If.html.
Wolfram Language. (1988). If. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/If.html