Special Forms (CNS) (Read 933 times)

Started by Just No Point, October 07, 2015, 02:35:52 pm
Share this topic:
Special Forms (CNS)
New #1  October 07, 2015, 02:35:52 pm
  • ******
The IfElse and Cond triggers handle bottom in a special way. Both of these triggers take the form:

<exp_cond> is a condition expression which, depending if it is nonzero, controls which of <exp_true> or <exp_false> gets returned. If bottom is produced in the expression that is not returned, then it does not propagate out to the rest of the expression. For instance, consider the expression IfElse(time > 0, 1.0/time, 2)). If time > 0, then the value of the expression is 1.0/time, which is a valid float value. If time = 0, then the value of the expression is 2, even though the unused branch divides by 0 and thus produces bottom.

However, even though the above IfElse trigger never returns bottom, it still has an annoying feature: the division by 0 still generates a warning to the debug output. This is because IfElse evaluates all its arguments, even the unused ones. In contrast, Cond will only evaluate the arguments that it actually uses. Thus, if we rewrote our expression as Cond(time > 0, 1.0/time, 2), the argument 1.0/time would never get evaluated when time was 0, and thus no warning would be generated.

You may wonder when to use Cond versus IfElse. The answer is that you almost always want to use Cond, unless one of <exp_true> or <exp_false> has a side effect that you need. In other words, if you are doing a variable assignment within one of the branches that always needs to be executed, regardless of the value of <exp_cond>, then you need to use IfElse. Otherwise, you should use Cond, especially for the purposes of isolating bottom.
Last Edit: October 07, 2015, 02:41:05 pm by Just No Point