Forth is an old language, with the first published specification in 1970, and earlier development going back to the late 1950’s. It found considerable success in the early days of personal computing due to its ability to run on very limited hardware. Also, Forth had its own simple built-in ‘operating system’ for handling files using blocks of disk-mapped memory. This enabled code to be developed in small ‘screens’ (often 16 lines x 64 characters). Combined with Forth’s unmatched interactivity, this development environment was much loved by most who used it.
Forth is interesting for two more reasons.
First, it has both a compiler and an interpreter available at all times. One switches between the two with ‘:’ and ‘;’ characters. Consider the following line of Forth code:
: SQUARE DUP * ;
The ‘:’ begins compiling, appending a new definition, called a ‘word’, into the dictionary. DUP duplicates a number, the ‘*’ multiplies it by its original self (thus squaring it), and the ‘;’ ends compiling, returning to the interpreter user prompt. A new keyword has just been added to Forth, thus extending the language !
Second, Forth is a ‘concatenative’ language. In more familiar languages (called ‘applicative’), such as C and Python, functions are applied to data stored in named locations. In Forth, the data are in a common, shared, flexible entity: the ‘stack’. This shared memory is available to each word upon entry, and any work done by the word is left in the (possibly) modified stack. The program simply consists of words chained together, from simple to complex, with the program finally run by the last defined word, which sits on top of the hierarchy. This is a very ‘natural’ way of programming, which I say more about here. Using our sample code from above, we could enter the following line at the interpreter prompt:
5 SQUARE .
5 simply puts that number on top of the stack. SQUARE executes our previously compiled word. The ‘.’ takes the number on the top of the stack and prints it:
A little more on this intriguing language.
Original Forth is a bit Spartan. Computers have come a long way in the past few decades. Machines that once filled entire desktops and weighed many pounds have given way to marvels like the Raspberry Pi. On the software side, several modern versions of Forth now give us much more comfort and power. Gone are the blocks and screens (although they still lurk for the nostalgic few). Full-blown operating systems like Linux have grown into indispensable work spaces. Far fewer wheels need to be re-invented.
One big, modern, standard, and popular Forth is GNUforth (gforth).
To install it on the pi:
sudo apt-get install gforth
To enter the interpreter, print the available words list, do a quick test, and then exit:
: square dup * ;
5 square .
Welcome to the amazing world of Forth.
An example of Forth in action: Monte Carlo Simulation