The Forth Programming Language
Forth is a stack-based, concatenative language made by Chuck Moore. Starting its life as an ad-hoc language to control telescopes, it was formalized into a full-fledged language and development environment by collaborators Elizabeth Rather and others, writing documentation and manuals along the way.
Being stack-based and concatenative, writing a parser and compiler for Forth is greatly simplified, making it a great alternative to C for writing low-level programs. It gives all the space and speed necessary for microcontroller code with all the benefits of a dynamic language.
Artihmetic Operations | word^1 |
---|---|
addition | + |
subtraction | - |
multipiclation | * |
division | / |
Forth is written in Reverse-Polish Notation, or Postfix Notation. That means that a function’s operands come before the function name:
Forth
5 5 + \\ leaves 10 on the top of the stack
Breaking the above down into its components:
Command | Stack | Note |
---|---|---|
5 | 5 | Literal |
5 | 5, 5 | Literal |
+ | 10 | Add two numbers on the stack |
\ | 10 | Ignore text till end of line (comment) |
One defines new words with the :
, a colon, and ends the “colon
definitions” with a ;
, a semicolon:
Forth
: square ( n -- n' ) dup * ;
Although it is technically optional, it is considered good coding
practice in Forth to include a stack-effect comment, denoted with
parens (
and )
, that describes the expected input items from the
stack, and the outputs it leaves behind.
The “concatenative” property of Forth comes from it being in reverse-polish notation and the fact that it uses a stack for passing arguments around. There is little to no syntax to speak of, only chains of commands, one after the other, as one could see in the simple example above. Those same chains of words could then be defined as new words, and so on. It gives one a pretty powerful language with very little overhead.
One can assign constants like so:
Forth
50 constant const_name \ This declares and assigns the constant
const_name \ leaves a copy of the data on the stack
And variables like so:
Forth
variable var \ declare variable
20 var ! \ store (! word) 20 into var
var @ \ access (@ word) contents of var, place on stack
var \ leave address of var on stack
Links
pForth Portable Forth implementation written in ANSI C
Simple Forth, an online book that “attempts to teach the rudiments of Forth.”