The REXX Calculator

By Dave Schnee

Every AS/400 (and many other machines with IBM-supplied operating systems) have REXX interpreters built-in. What seems to be a very well kept secret is that REXX is a very capable and versatile command language with full access to all system facilities. That is because REXX is able to execute all host commands.

What is different, however, is that REXX is not a compiled language -- it is always interpreted. Moreover, it is permissible to create a REXX command in a REXX variable and then execute the command you have just created. Since the created command can be anything REXX can do, there are some unique and powerful possibilities. The following calculator is just one.

To Implement the calculator, I use a CMD source member to allow prompting and command line entry.

calculate '4+(6*5.876)/17'
or
CALCULATE EXPRESSION('4+(6*5.876)/17')

Also, I can prompt for the calculate command just like any other AS/400 command. Remember to limit your expression to valid mathematical form using "+" to add, "-" to sub, "/" to divide, "*" to multiply, "**" to exponentiate (only to an integer power, though) and parentheses as needed for the ordering of execution as needed.

The Instructions and Actual Code

First, create a REXX Source Member (I used member CALCULATOR in QGPL/QREXSRC, but you can use any member name in any source file):

1234567890123456789012345678901234567890123456789012345678901234
/* REXX Procedure to evaluate a numeric expression            */
/* Input (through a command) is EXPRESSION('nnnnnnnnn')       */
/*                 where nnnnnnnnn is the user's input        */
numeric digits 31
arg extarg
myval = "value =" extarg
interpret myval
say "value of" extarg "=" value
say
return 0

expression:
arg arginput
v = "value2 =" arginput
interpret v
return value2
end function

Next, create a CMD Source Member (I used member CALCULATOR in QGPL/QCMDSRC, but you can use any member name in any source file):

1234567890123456789012345678901234567890123456789012345678901234
     CMD       PROMPT('Simple numeric calculator')
     PARM      KWD(EXPRESSION) TYPE(*CHAR) LEN(256) MIN(1) +
                 PROMPT('Expression to evaluate')


Now, create the CALCULATE command using *REXX as the program to process the command and referring to the REXX Source Member:
REXSRCFILE(QGPL/QREXSRC) REXSRCMBR(CALCULATOR) TEXT('Command to evaluate a numeric expression')

Try it -- you may like it.

Dave Schnee can be reached at dave@schnee.com.

Use your browser's back button to return to the Tips and Techniques Page, or click on any link on the left.