stack-based squishies

Forth is a stack based programming language from the 70s, but that still holds up 50 years later!

If you want to play along at home, install a forth of your choice! The GNU project has [gforth], one of the few FOSS ANSI Forth implementations.

Or, better yet, use [UF], which is a forth implementation for {UXN}!

Stacks are the core concept in Forth, and similar languages. They're also known as LIFO (Last-In, First-Out) structures, because that's how they work!

Intro to the stack and basic Forth :>

You interact with the stack by pushing data onto it! This is the easiest operation in forth, you just write your data.

1 2 3 pushes 1, 2, and 3 onto the stack!

Now, . pops the top item off of the stack, and prints it out for you.

What do you think . . . would print now?

1 2 3 . . . returns 3 2 1 ok! It's backwards because that's how stacks work, Last In, First Out! The ok is the forth implementation telling you that it's ready for more input.

If we want to do anything with the stack, we use words! Words are what forth calls any operations. Words also have "arrity", which is their effect on the stack.

For example, + could be notated as ( a b - c ). This tells us that it takes in 2 things on the stack, and returns one.

All math in forth is in [Reverse Polish Notation], where you put operators after their operands. For example, 1 + 1 is 1 1 +. Because of this, you don't need parentheses, because all order of operations is defined by reading left to right.

Heres a more complex example of how to rewrite math in RPN: (1 + 5) / ((2 9) - 3) becomes 1 5 + 2 9 3 - /. While this might seem more complex at first, it's equivalent to the first equation, without a need for parentheses.

Building your own words

For now, we've only used things built into forth. Forth can let you define your own words tho! And it's super easy too!

Forth has a "compile mode" which you can enter by using the word : and exit by using ;. After : you have to give your new word a name, but after that, you just write forth!

Here's a word that squares a number: : square ( n - n^2 ) dup * ;

This is a pretty simple definition.

Chuck Moore is a personal hero <3

duskos

cool forth based OS

Links

incoming(2) | december fourth | icbinf