Introduction
This small ebook is here to teach you a programming language called Forth. Forth is a language unlike most others. It’s not functional or object oriented, it doesn’t have type-checking, and it basically has zero syntax. It was written in the 70s, but is still used today for certain applications.
Why would you want to learn such an odd language? Every new programming language you learn helps you think about problems in new ways. Forth is very easy to learn, but it requires you to think in a different way than you’re used to. That makes it a perfect language to broaden your coding horizons.
This book includes a simple implementation of Forth I wrote in JavaScript. It’s by no means perfect, and is missing a lot of the functionality you’d expect in a real Forth system. It’s just here to give you an easy way to try out the examples. (If you’re a Forth expert, please contribute here and make it better!)
I’m going to assume that you know at least one other programming language, and have a basic idea of how stacks work as a data structure.
Adding Some Numbers
The thing that separates Forth from most other languages is its use of the stack. In Forth, everything revolves around the stack. Any time you type a number, it gets pushed onto the stack. If you want to add two numbers together, typing + takes the top two numbers off the stack, adds them, and puts the result back on the stack.
Let’s take a look at an example. Type (don’t copy-paste) the following into the interpreter, typing Enter after each line.
1 2 3
Every time you type a line followed by the Enter key, the Forth interpreter executes that line, and appends the string ok to let you know there were no errors. You should also notice that as you execute each line, the area at the top fills up with numbers. That area is our visualization of the stack. It should look like this:
... continue reading