Forth is an untyped programming language that heavily relies on the stack: data will be stored onto the stack before they are operated upon. Forth is the perfect programming language for hardware engineers:
Although Forth source code can be stored into files in order to be compiled and executed, the examples shown in this articles are to be run interactively. All examples were tested using the GNU implementation of Forth, named Gforth which can be retrieved from the Git repository executing the following:
$> git clone https://git.savannah.gnu.org/git/gforth/
The user should read the ‘INSTALL.md’ file in order to know how to build and install GForth. At this present stage, the following are to be executed on Linux to get the Forth environment up and running:
$> source ./install-deps.sh
$> ./BUILD-FROM-SCRATCH
# The following is not mandatory
$> sudo make install
Start the environment by running ‘gforth’ and exit the program by typing ‘bye’ or pressing the ‘Ctrl+d’ key combination. Typing numbers will place them onto the stack:
6 7 8 ok 3
Type ‘.s’ to print the content of the stack and its size (computer output is appended right after ‘.s’):
.s <3> 6 7 8 ok 3
The line above states that the stack contains three elements: 6, 7 and 8 having the rightmost element on top of the stack. As this language is a stack based one, arithmetic operators always apply to the top two stack items. Therefore, given the numbers 10, 2 and 3, to get the number 6 as the result of ‘2 * 3’ the following sequence of command is to be issued:
10 2 3
*
.s <2> 10 6 ok 2
The two most important facts are the following:
As operators manipulate the top of the stack, this might need to be rearranged every now and then by using any of the following stack oriented keywords:
Even though most of the work can be done on the stack without having to use variables, they can still be defined as they may be useful to store values that have to be accessed by multiple words. The following line defines a variable: variable price
The next line assign a value to it which is stored at the memory location pointed by the variable:
15000 price !
The next line copies the variable onto the top of the stack:
price @
Therefore, the final result of the following will be 27000:
variable price
15000 price !
12000
price @
+
.s <1> 27000 ok 1
As stack based language, Forth can: