13 January 2016

Lesson 5 – Easy calculations in 8th

Infix notation


When we learn to calculate in school, we learn the infix method.

Example:     2 + 3     (which is 5).

In this example the + operator is between the 2 numbers to be added together.

Postfix notation as used in 8th

In 8th (and other Forth dialects) we always use postfix.

Example:     2 3 +      (which is 5).

The SED of + is \ x y – z which means: + takes 2 values (x and y) from the stack, calculates the sum (z), and puts that result back on the stack.

As we saw earlier when we enter 2 3 these two items are put on the stack. Look at the REPL:
Here we enter the two data values 2 and 3 on the stack.


Here you see these 2 values (right hand column).

Now we execute the + word.

The original items are gone and the result value of + is now on the stack.




8th allows us to enter such expressions differently:








All these 3 methods are equal as 8th is concerned.

More calculation operators

Now we have seen one calculating word in action it should be easy to try other words as well. We will show you a few in the REPL.

Subtract using the word
SED of is \ x y – z where z = x y.





Multiply using the * word
SED of * is \ x y z where z = x * y.





Divide using the / word
SED of / is \ x y – z where z = x / y.





As you can see in those examples we can also issue the .s word on the same line as well. 8th really doesn’t matter!

Operator precedence

In most programming languages there is an impressive chart of the operator precedence rules. That chart tells you what to expect when you enter an expression like this: 24 - 8 / 2 + 3 * 4

In most languages the rules say:  first multiply, then divide, then add and subtract. So the result would be (step 1) 24 - 8 / 2 + 12 = (step 2) 24 - 4 + 12 = (step 3) 32.

In 8th we don’t need such a chart, since it is chrystal clear what is going to happen:
24 8 2 / - 3 4 * +

When 8th evaluates this it evaluates from left to right:
1. evaluate 8 2 / and put 4 back. So the resulting expression is: 24 4 3 4 * +
2. evaluate 24 4 and put 20 back. So the resulting expression is: 20 3 4 * +
3. evaluate 3 4 * and put 12 back. So the resulting expression is: 20 12 +
4. evaluate 20 12 + and put 32 back. The result 32 is left on the stack.

More info about 8th

There is a central website for 8th here: http://8th-dev.com/

Video

Watch the complimentary video here

No comments:

Post a Comment