Chapter 6. Ifs and Elses

Understanding how conditionals are implemented in Ripley requires knowing how executable arrays work, and the system dictionary values of true and false.

First is the 'if' operand, which takes two operands. The first is a boolean value, then second is an executable array. For example, this code block will always execute:

Example 6-1. Always true conditional

true { "Always prints" print } if

The next example never prints because the boolean is negative.

Example 6-2. Always false conditional

false { "Never prints" print } if

Well, that's great, if you want a conditional that is not conditional. So we need some comparison operators. Which is where eq, lt, le, gt, and ge come in handy. These functions take two operands off the operand stack, then push one boolean value back onto the operand stack. Here is an example of a function that prints a string if the value 'passed' in on the stack is greater than ten.

Example 6-3. Greater than ten printer

/geTenPrinter { 10 gt { "Greater than 10\n" print } if } def
5 geTenPrinter
15 geTenPrinter

If we have an if then else type of syntax then we could implement a printer that prints out one string if it's greater than 10 and another if it's less. This is where the ifelse operator comes in handy. It takes three operands off the operand stack; the first is a boolean, the next an executable array that is executed if the boolean is true, and the next is an executable array that is executed if the value is false. (An easy way to remember which one is which is by matching the first executable array with the 'if' portion of the name and the second executable array with the 'else' portion.) Here is an example of the geTenPrint implemented using 'ifelse'.

Example 6-4. Greater than ten printer (ifelse version)

/geTenPrinter { 10 gt { "Greater than 10\n" } { "Less than 10\n" } ifelse print } def
5 geTenPrinter
15 geTenPrinter