← Back to all projects

LEARN FORTH A DIFFERENT PATH

Forth is not a mainstream language. You won't use it to build the next hit mobile app or website. So why learn it? Because learning Forth is a mental exercise that fundamentally changes how you view programming. It's the ultimate minimalist toolkit.

Learn Forth: A Different Path to Programming

Goal: To understand the philosophy and mechanics of the Forth programming language by embracing its core concepts: the stack, the dictionary, and radical extensibility. You will learn to “think in Forth” by building up complexity from simple, interactive components.


Why Learn Forth?

Forth is not a mainstream language. You won’t use it to build the next hit mobile app or website. So why learn it? Because learning Forth is a mental exercise that fundamentally changes how you view programming. It’s the ultimate minimalist toolkit.

  • It Teaches You About Stacks: Forth is a “stack-based” language. Every operation—from arithmetic to I/O—is done by manipulating data on a stack. Mastering Forth gives you an intuitive understanding of stack machines, which is how many virtual machines (like the JVM) and real processors work under the hood.
  • It Blurs the Line Between Compiling and Interpreting: Forth is an interactive, extensible system. You define new words, and they immediately become part of the language, available for you to use. You are constantly teaching the language new tricks. In a sense, programming in Forth is the process of building a language specific to your problem.
  • It’s “Down to the Metal” at a High Level: Forth is used in places where resources are tight and direct hardware control is needed, such as in bootloaders (Open Firmware), space probes, and embedded controllers. It gives you low-level power with high-level, interactive development.
  • It’s an Exercise in Minimalism: A complete Forth system can be implemented in just a few kilobytes. Everything is built from a tiny core of primitive words. It forces you to think about building complex systems from the smallest possible, reusable parts.

After this journey, you will have a new appreciation for what a programming language really is, and you’ll have a powerful new mental model for solving problems.


Core Concept Analysis

To learn Forth, you must unlearn some habits from other languages.

The Stack: The Center of the Universe

In most languages, you write result = (1 + 2) * 3. The + and * are “infix” operators, and you store the result in a named variable.

In Forth, you don’t use variables as much. You use the stack. The equivalent Forth code is: 1 2 + 3 *. This is called Reverse Polish Notation (RPN).

  1. 1: Push 1 onto the stack. Stack: [1]
  2. 2: Push 2 onto the stack. Stack: [1, 2]
  3. +: The + word takes the top two items from the stack (1 and 2), adds them, and pushes the result (3) back on. Stack: [3]
  4. 3: Push 3 onto the stack. Stack: [3, 3]
  5. *: The * word takes the top two items (3 and 3), multiplies them, and pushes the result (9) back on. Stack: [9]

Everything revolves around the stack. The most important skill in Forth is visualizing the state of the stack after each word.

The Dictionary and Words

A Forth program is a collection of “words.” A word is just a function. You define new words using :.

: SQUARE DUP * ;

This defines a new word called SQUARE.

  • : begins a new definition.
  • SQUARE is the name of the new word.
  • DUP is a built-in word that duplicates the top item on the stack.
  • * is the multiplication word.
  • ; ends the definition.

Now, SQUARE is part of the language. You can type 5 SQUARE and the result 25 will be left on the stack.

Interactivity: The REPL

Forth is almost always used with an interactive REPL (Read-Eval-Print-Loop). You type a word, Forth executes it, and shows you the result. This encourages a highly iterative and exploratory style of development.


Project List

We will use Gforth, a popular and complete Forth implementation. You can install it on most operating systems. The projects are designed to force you to think in terms of the stack.


Project 1: The RPN Calculator

  • File: LEARN_FORTH_A_DIFFERENT_PATH.md
  • Main Programming Language: Forth
  • Alternative Programming Languages: N/A
  • Coolness Level: Level 2: Practical but Forgettable
  • Business Potential: 1. The “Resume Gold”
  • Difficulty: Level 1: Beginner
  • Knowledge Area: Forth / Stack Machines
  • Software or Tool: Gforth
  • Main Book: “Starting Forth” by Leo Brodie

What you’ll build: You won’t write a file for this project. You will use the Gforth interpreter as a powerful RPN calculator to solve mathematical formulas. The goal is to get comfortable with postfix notation and basic stack manipulation.

Why it teaches the fundamentals: This project is the essential first step. If you can’t think in RPN, you can’t use Forth. This forces you to visualize the stack and use the core stack manipulation words (DUP, SWAP, DROP, ROT) to get your data in the right order for operations.

Core challenges you’ll face:

  • Converting infix formulas to RPN → maps to learning to think in a postfix way
  • Visualizing the stack in your head → maps to the single most important skill in Forth
  • Using stack “shufflers” → maps to mastering DUP, SWAP, ROT, OVER
  • Using the Gforth REPL → maps to using .S to see the stack and . to print the top value

Key Concepts:

  • RPN: The foundation of Forth syntax.
  • Stack Manipulation: “Starting Forth” Chapters 1 & 2.

Difficulty: Beginner Time estimate: A few hours Prerequisites: None.

Real world outcome: You will have a fluid and intuitive grasp of stack-based computation. You’ll be able to type 5 9 * 32 - 5 9 */ . into Gforth and correctly get the result for converting 9°C to Fahrenheit.

Implementation Hints:

  1. Start Gforth: Just type gforth in your terminal.
  2. See the Stack: The .S word is your best friend. It non-destructively prints the current state of the stack.
  3. Basic Arithmetic: 10 5 + . (prints 15).
  4. Stack Words to Master:
    • DUP: ( a – a a ) Duplicates the top item.
    • DROP: ( a – ) Throws away the top item.
    • SWAP: ( a b – b a ) Swaps the top two items.
    • OVER: ( a b – a b a ) Copies the second item to the top.
    • ROT: ( a b c – b c a ) Rotates the top three items.
  5. Challenge: Convert the formula (a+b) * (c-d) to RPN.
    • Answer: a b + c d - *

Learning milestones:

  1. You can solve a multi-step formula without errors → You understand RPN.
  2. You use DUP to square a number (DUP *) → You’re thinking about data reuse on the stack.
  3. You use SWAP to get arguments in the right order for division → You’re actively managing the stack.
  4. You can predict the stack state before typing .S → Your mental model of the stack is working.

Project 2: Defining Your World of Words

  • File: LEARN_FORTH_A_DIFFERENT_PATH.md
  • Main Programming Language: Forth
  • Alternative Programming Languages: N/A
  • Coolness Level: Level 3: Genuinely Clever
  • Business Potential: 1. The “Resume Gold”
  • Difficulty: Level 1: Beginner
  • Knowledge Area: Forth / Abstraction
  • Software or Tool: Gforth
  • Main Book: “Starting Forth” by Leo Brodie

What you’ll build: A .fs file containing a small library of your own custom Forth words. You’ll define words for common mathematical and logical operations, such as SQUARE, CUBE, IS-NEGATIVE?, AVERAGE, etc.

Why it teaches abstraction: This project is the second pillar of Forth: extensibility. You learn that a Forth program is nothing more than extending the dictionary with words that are specific to your problem. You are building your own mini-language.

Core challenges you’ll face:

  • Using the colon definition syntax → maps to learning : and ;
  • Factoring common patterns into new words → maps to the core of Forth programming style
  • Adding comments to your code → maps to using ( and ) for stack comments
  • Loading your file into Gforth → maps to using include my_words.fs

Key Concepts:

  • The Dictionary: “Starting Forth” Chapter 3.
  • Factoring: The process of breaking down problems into smaller and smaller words.

Difficulty: Beginner Time estimate: Weekend Prerequisites: Project 1.

Real world outcome: A file of custom words you can load into Gforth. You can then use your own words interactively. 10 AVERAGE-WITH-5 could be a word you write.

Implementation Hints:

  1. Creating a Word:
    \ This is a comment. The word SQUARE expects one number on the stack.
    \ ( n -- n*n )  <-- This is a stack effect comment. It's a crucial convention.
    : SQUARE DUP * ;
    
  2. Stack Effect Comments: The ( before -- after ) comment is the most important documentation you can write. It explains what your word does to the stack.
  3. Chaining Definitions:
    \ ( n -- n*n*n )
    : CUBE DUP SQUARE * ;
    

    Notice how CUBE is defined using the SQUARE word you just made. This is the essence of Forth.

  4. Boolean Logic: Forth doesn’t have a true or false keyword. It uses numbers: 0 is false, and -1 (all bits set) is true. Comparison words like < or > leave a 0 or -1 on the stack.
    \ ( n -- flag )
    : IS-NEGATIVE? 0 < ;
    

Learning milestones:

  1. You have defined and used a new word successfully → You understand the colon definition.
  2. You have created a new word that uses another custom word you wrote → You are thinking about factoring.
  3. You have written clear stack effect comments for all your words → You are documenting your code in the Forth style.
  4. You can load your file and use your entire new vocabulary → You have created a library.

Project 3: Conditionals and Loops - Controlling the Flow

  • File: LEARN_FORTH_A_DIFFERENT_PATH.md
  • Main Programming Language: Forth
  • Alternative Programming Languages: N/A
  • Coolness Level: Level 3: Genuinely Clever
  • Business Potential: 1. The “Resume Gold”
  • Difficulty: Level 2: Intermediate
  • Knowledge Area: Forth / Control Flow
  • Software or Tool: Gforth
  • Main Book: “Starting Forth” by Leo Brodie

What you’ll build: A set of words that demonstrate control flow. You’ll write a word that uses IF/ELSE/THEN to print a message based on a flag. Then you’ll write a word that uses a DO/LOOP to print numbers from 1 to 10.

Why it teaches control flow: Forth’s control flow words are bizarre at first glance. They are not syntax; they are words that manipulate the instruction pointer at compile time. This project demystifies them and shows how they still operate on the stack.

Core challenges you’ll face:

  • Understanding IF/ELSE/THEN → maps to realizing that IF consumes a flag from the stack
  • Using DO/LOOP → maps to learning about the special return stack used for loop counters
  • Creating a definite loop → maps to the limit start DO ... LOOP structure
  • Creating a more complex loop with LEAVE or +LOOP → maps to advanced loop control

Key Concepts:

  • Immediate Words: Some words like IF and LOOP execute during compilation, not at runtime.
  • The Return Stack: A second stack used to hold loop counters and function return addresses, separate from the data stack.

Difficulty: Intermediate Time estimate: Weekend Prerequisites: Project 2.

Real world outcome: Words in your library that can make decisions and repeat actions. You’ll be able to run a word COUNTDOWN that prints “10 9 8 … 1 BLASTOFF!”.

Implementation Hints:

  1. IF/ELSE/THEN:
    : GUESS-THE-NUMBER ( n -- )
      7 = IF ." You got it!" CR
      ELSE   ." Try again." CR
      THEN ;
    

    The IF consumes the boolean flag left by the = word. . is the word to print a number, ." prints a string. CR prints a newline.

  2. DO/LOOP: The loop runs from a start value up to (but not including) a limit. The loop counter, I, is accessible.
    : COUNT-TO-TEN
      11 1 DO  \ Loop from 1 to 11
        I .   \ Print the loop index
      LOOP ;
    
  3. The Return Stack: The DO/LOOP indices are kept on the return stack. You can see it with .R. Be careful not to mess up the return stack, or your program will crash!

Learning milestones:

  1. You can write a word that prints different things based on an input value → You understand IF/THEN.
  2. You can write a loop that prints a sequence of numbers → You understand DO/LOOP.
  3. You can access the loop counter I and use it in a calculation → You understand the role of the return stack.
  4. You begin to see IF and DO not as syntax, but as functions that have stack effects → You are truly thinking in Forth.

Project 4: Building a Forth in Python

  • File: LEARN_FORTH_A_DIFFERENT_PATH.md
  • Main Programming Language: Python
  • Alternative Programming Languages: C, Go, JavaScript
  • Coolness Level: Level 5: Pure Magic (Super Cool)
  • Business Potential: 1. The “Resume Gold”
  • Difficulty: Level 4: Expert
  • Knowledge Area: Compilers / Interpreters / VMs
  • Software or Tool: Your favorite text editor and Python interpreter.
  • Main Book: “Thinking Forth” by Leo Brodie & Create Your Own Computer Language tutorial.

What you’ll build: A simple, working Forth interpreter, written in Python. It will have a data stack, a dictionary, a REPL, and a small set of primitive words (like +, DUP, . etc.) implemented in Python. You will then define more complex Forth words using your own interpreter.

Why it’s a capstone project: To truly understand a system, build it. This project forces you to implement every core concept of Forth: the stacks, the dictionary, the parser (outer interpreter), and the execution mechanism (inner interpreter). It’s a masterclass in language implementation.

Core challenges you’ll face:

  • Implementing the Data Stack → maps to a simple Python list with append and pop
  • Designing the Dictionary → maps to a Python dictionary or a linked list of custom “Word” objects
  • Writing the Outer Interpreter (Parser) → maps to a loop that reads a line, splits it by spaces, and processes each word
  • Implementing Primitives vs. Defined Words → maps to distinguishing between words whose logic is in Python and words whose logic is a list of other words

Key Concepts:

  • Direct vs. Indirect Threaded Code: A deep dive into interpreter design.
  • Metacompilation: The process of defining a language in terms of itself.

Difficulty: Expert Time estimate: 1-2 weeks Prerequisites: All previous projects. Solid understanding of Python or another high-level language.

Real world outcome: A Python script that you can run to get a working Forth REPL. You can type 1 2 + . and see 3. You can type : SQUARE DUP * ; and then 5 SQUARE . and see 25. You will have built a living language.

Implementation Hints:

  1. The Engine:
    class ForthEngine:
        def __init__(self):
            self.stack = []
            # Dictionary maps word names to functions or lists of words
            self.dictionary = {
                '+': lambda: self.stack.append(self.stack.pop() + self.stack.pop()),
                '.': lambda: print(self.stack.pop()),
                # ... other primitives ...
            }
        def eval(self, code_string):
            words = code_string.split()
            for word in words:
                if word in self.dictionary:
                    self.dictionary[word]()
                else:
                    self.stack.append(int(word)) # Simple number parsing
    
  2. Handling Colon Definitions: This is the tricky part. When your parser sees :, it needs to switch from “interpreting” mode to “compiling” mode. It should read the next word as the name, and then all subsequent words (until ;) become the definition (a list of strings) which gets stored in the dictionary.
  3. The Inner Interpreter: When you execute a user-defined word (like SQUARE), its definition is a list of other words (['DUP', '*']). Your engine must then execute these words in sequence.

Learning milestones:

  1. Your interpreter can perform basic arithmetic → You have a working stack and primitive words.
  2. Your interpreter can handle colon definitions and define a new word → You have a working compiler/interpreter switch.
  3. You can execute a user-defined word → You have a working inner interpreter.
  4. You define a Forth word in your Forth that uses IF/THEN → You have reached meta-enlightenment. You have built a self-hosting language.

Project Comparison Table

Project Difficulty Time Core Focus Why it’s Important
RPN Calculator Level 1: Beginner Hours Stack & RPN Teaches the fundamental thought process.
Defining Words Level 1: Beginner Weekend Abstraction Shows how Forth programs are constructed.
Control Flow Level 2: Intermediate Weekend Language Mechanics Demystifies Forth’s unique control words.
Build a Forth Level 4: Expert 1-2 weeks Language Implementation The ultimate “I understand it” project.

Recommendation

Forth is a language of the mind. The projects must be done in order, as they are designed to build a specific mental model.

  1. Spend a few hours on Project 1: The RPN Calculator. Do not move on until you stop mentally translating from infix and start thinking in RPN.
  2. Immediately move to Project 2: Defining Your World of Words. This is the natural extension of the calculator and where the “language building” aspect begins.
  3. Tackle Project 3: Control Flow to get the tools you need for more complex logic.
  4. Finally, when you feel you understand how to use Forth, embark on Project 4: Building a Forth. This will be a challenging but deeply enlightening experience that will solidify every concept you’ve learned.

Summary

Project Main Programming Language
The RPN Calculator Forth
Defining Your World of Words Forth
Conditionals and Loops - Controlling the Flow Forth
Building a Forth in Python Python