next | previous | forward | backward | up | top | index | toc | Macaulay2 web site
Macaulay2Doc > The Macaulay2 language > conditional execution

conditional execution -- if-then-else statements

The basic way to control the execution of code is with the if expression. Such an expression typically has the form
if X then Y else Z
and is evaluated as follows. First X is evaluated. If the result is true, then the value of Y is provided, and if the result is false, then the value of Z is provided. An error is signalled if the value of X is anything but true or false.
i1 : (-4 .. 4) / 
          (i -> if i < 0 then "neg" 
               else if i == 0 then "zer" 
               else "pos")

o1 = (neg, neg, neg, neg, zer, pos, pos, pos, pos)

o1 : Sequence
The else clause may be omitted from an if expression. In that case, if value of the predicate X is false, then null is provided as the value of the if expression.
i2 : (-4 .. 4) / 
          (i -> if i < 0 then "neg" 
               else if i == 0 then "zer")

o2 = (neg, neg, neg, neg, zer, , , , )

o2 : Sequence
There are a variety of predicate functions (such as <, used above) that yield true or false and can be used as the predicate in an if expression. For a list, see Boolean. Boolean results may be combined with not, and, and or.