IF-THEN/ELSE Expression |
IF logic-expression THEN expression-2 ELSE expression-3
The IF-THEN/ELSE expression evaluates the logical expression logic-expression and returns the result of evaluating the second or third operand expression according to the logical test result. If the logic-expression is true (nonzero and nonmissing), then the result of evaluating expression-2 is returned. If the logic-expression is false (zero or missing), then the result of evaluating expression-3 is returned. The other subexpression that is not selected is not evaluated.
An ELSE clause is matched during parsing with the nearest IF-THEN clause that does not have a matching ELSE. The ELSE clause can be omitted for numeric expressions; the resulting IF-THEN is handled as if a default ELSE 0 clause were supplied.
Use the IF-THEN/ELSE expression to handle special cases in models. For example, an inventory model based on discrete time periods might require special handling for the first or last period. In the following example the initial inventory for the first period is assumed to be fixed:
proc optmodel; number T; var inv{1..T}, order{1..T}; number sell{1..T}; number inv0; . . . /* balance inventory flow */ con iflow{i in 1..T}: inv[i] = order[i] - sell[i] + if i=1 then inv0 else inv[i-1]; . . .
The IF-THEN/ELSE expression in the example models the initial inventory for a time period . Usually the inventory value is the inventory at the end of the previous period, but for the first time period the inventory value is given by the inv0 parameter. The iflow constraints are linear because the IF-THEN/ELSE test subexpression does not depend on variables and the other subexpressions are linear.
IF-THEN/ELSE can be used as either a set expression or a scalar expression. The type of expression depends on the subexpression between the THEN and ELSE keywords. The type used affects the parsing of the subexpression that follows the ELSE keyword because the set form has a lower operator precedence. For example, the following two expressions are equivalent because the numeric IF-THEN/ELSE has a higher precedence than the range operator (..):
IF logic THEN 1 ELSE 2 .. 3 (IF logic THEN 1 ELSE 2) .. 3
But the set form of IF-THEN/ELSE has lower precedence than the range expression operator. So the following two expressions are equivalent:
IF logic THEN 1 .. 2 ELSE 3 .. 4 IF logic THEN (1 .. 2) ELSE (3 .. 4)
The IF-THEN and IF-THEN/ELSE operators always have higher precedence than the logic operators. So, for example, the following two expressions are equivalent:
IF logic THEN numeric1 < numeric2 (IF logic THEN numeric1) < numeric2
It is best to use parentheses when in doubt about precedence.