Friday, November 4, 2011

Boolean Switch-setting

'Switches' are an important logic element in many languages.  They allow the programmer to quickly and easily direct the flow of logic.  The classic IF-THEN-ELSE is even represented on flowcharts by the diamond-shaped 'switch box'.  The result is either true or false, '1' or '0'.  In fact, that classic IF-THEN-ELSE is very often used to set switches for later use when the values may have been changed by subsequent processing.  Switches often get set like this:

if A = B then sw.0equal = 1
         else sw.0equal = 0
There is another way, I think it's a better way, and it certainly cuts down on the keystroking, but it's not immediately obvious to newbies what's happening:
sw.0equal = A = B
Got it?  When A and B are equal — when 'A = B' is TRUE — sw.0equal gets set to '1', TRUE.  sw.0equal takes on the truth-value of the proposition 'A = B'.

My old friend, Ramon Faulk, taught me that trick back in the 1970s.  You have to be writing in a terse language like REXX or PL/I to be able to use it.  Good thing we're working in REXX, huh? ;-)

Note also that the content-addressible array "sw." is here suffixed with the glyph "0equal".  "0equal" is invalid as a variable name, so no maintainer can come along behind you, use "equal" as a variable, and dynamically redefine the meaning of "sw.equal".  I learned that one from Les Koehler, the first American to write a REXX program.  Unless you intend that content-addressible array suffix to be changeable, start it with any character that will prevent its use as a variable.

3 comments:

  1. I like the "variable = A = B" syntax as well ... but I generate it as "variable = (A = B)" which makes it much more readable for the newbie.

    It is always great to meet a fellow REXXer

    ReplyDelete
  2. Rather than use a stem variable for the switch name, I use a variable name prefixed with a "?" as in the example below:

    /* REXX */
    A=1; B=1
    ?C = (A = B)
    SAY 'C=' ?C
    IF ?C THEN
    SAY '!!! C = 1 !!!'
    ELSE
    SAY '~~~ C = 0 ~~~'

    ReplyDelete
    Replies
    1. Of course, then you can't set all switches OFF as by

      sw. = 0

      Delete