Contents

Forth Intro

This curious language heavily relies on stack (or two stacks). Despite it allows allocating data in variables and even arrays, you'll find yourself doing many operations on the main stack of interpreter. We remember that stack is a data structure into which values could be pushed and then popped in reversed order.

For example if interpreter encounters number, it is pushed onto stack. The word . (dot) means "pop" value out of the top of the stack and print it. Regard the statement:

10 20 50 . 60 . . .

It is going to print out first 50 then 60, 20 and 10. Stack works on "first-in-last-out" principle.

If binary operation is encountered, two values are popped from the stack, operation applied to them, then result is pushed back. For example:

20 30 40 + * .

will add 30 to 40 (so the stack contains 20 70 after addition) and then multiplies them and prints result 1400.

Language status: nowadays Forth is rarely if ever used - it was mainly important in days when computers had small memory and its interpreter could fit just a few kilobytes. However it left certain inheritance in the form of newer languages like Factor. Moreover Java Virtual Machine uses stack for operations just in very similar manner, so really are many machines, servers, sites and applications internally related - just since Java is one of the most popular languages nowadays.

Running

We are going to use pForth implementation.

There is an Online Interpreter for your convenience - just wait for it to launch the system and when it says "Ready" start interpreter with pforth command followed by <enter> key.

By default it prints stack content after each hit of enter key, this may be convenient at start.

Alternatively there is Forth button under solution area of task pages - just it runs in non-interactive mode.

Also it is possible to install "pForth" on your machine. Other versions also may work fine especially if you try to keep up with ANSI standard.

Further Features

It is possible to define our own words (in a manner of subroutines). Syntax starts with colon : word and ends with semicolon ; - both should be separated with spaces from content. Usually our custom word wants to pop parameters from the stack and push result instead. For example the word for rectangle perimeter, supposing two values (sides of rectangle) are on the stack before calling it.

: perimeter + 2 * ;

which could be used like this

100 150 perimeter .

hopefully this prints 500.

There are also control structures - conditionals and loops. However now it is the time to pass the turn to much more solid and fun manual:

Starting Forth by Leo Brodie

Note that you are not obliged to run carefully from beginning (though it is not bad idea) - you can use the book as reference, jumping to chapter on decisions or loops at your wish.