Defining Words

It's now time to write a small program in Forth. You can do this by defining a new word that is a combination of words we have already learned. Let's define and test a new word that takes the average of two numbers.

We will make use of two new words, : (colon), and ; (semicolon). These words start and end a typical Forth definition. Enter:

: AVERAGE ( a b -- avg ) + 2 / ;

Congratulations! You have just written a Forth program. Let's look more closely at what just happened. The colon told Forth to add a new word to its list of words. This list is called the Forth dictionary. The name of the new word will be whatever name follows the colon. Any Forth words entered after the name will be compiled into the new word. This continues until the semicolon is reached which finishes the definition.

Let's test this word by entering:

10 20 AVERAGE . | should print 15

Once a word has been defined, it can be used to define more words. Let's write a word that tests our word. Enter:

: TEST ( --) 50 60 AVERAGE . ;
TEST

Try combining some of the words you have learned into new Forth definitions of your choice. If you promise not to be overwhelmed, you can get a list of the words that are available for programming by entering:

words

Don't worry, only a small fraction of these will be used directly in your programs.