3.2. A little more math

The next thing to lear are the other math primitives; sub, mul and div. These are the operands for subtract, multiply, and divide. They all work like add, taking two operands from the operand stack, applying a transform (adding, subtracting, multiplying or dividing) and pushing the result back onto the operand stack.

Here is an example subtraction:

Example 3-2. Subtracting 1 for 2

Program Listing

2 1 sub print

Program Output


An example multiplication:

Example 3-3. Multiplying 2 by 10

Program Listing

2 10 mul print

Program Output


An example division:

Example 3-4. Dividing 10 by 5

Program Listing

10 5 div print

Program Output


How about more complex formulae? Well, it's really a matter of creating a sequence of operands that manipulate the stack correctly. For example, how about (1+2)*10:

Example 3-5. Evaluating (1+2)*10

Program Listing

1 2 add 10 mul print

Program Output


Is it as easy as (1+2)*10, maybe not, but it is a sytem capable of building an arbitrary simple equation.