Drawing with Forth
In this tutorial, you'll learn basic Forth by drawing graphics with a turtle.
💡 Click the Run button next to the examples to run the code, or click the Run button at the top to run all the code on this page.
❕ This is not a real tutorial, but a demo of a WAForth notebook, and perhaps a glimpse of what an interactive Forth tutorial using notebooks could look like.
The stack
Forth is a stack-based language. Numbers are put on the stack, and words pop them off the stack (and put new ones on the stack) again.
For example, to take the sum of 8 and 14, put both numbers on the stack, and call +
. To pop the result of the stack and print it out, use .
:
Drawing lines
Instead of printing numbers to output, we can also draw lines.
The FORWARD
word pops the number of the stack, and moves a turtle forward while drawing a line:
Let's now also turn the turtle 90 degrees, and create a complete square:
Creating your own words
We can create our own parameterized word that draws a square of the given size:
Loops
Forth also has loops using DO
and LOOP
:
Combining words
We can create more complex figures by using the SQUARE
word from above, and repeating it.
💡 Play with the numbers in
FLOWER
to create variations of the flower
Recursion
Words can also call themselves:
We can make a small variation of the above recursive program, where the lines become longer instead of shorter.
To avoid hard-coding some constants in the code, we use the word CONSTANT
to define a new constant (ANGLE
) to turn.
💡 Change the constant
ANGLE
to 91 and see what happens.
Fractals
You can create more complex recursive drawings, called fractals.
A famous fractal is the Koch snowflake.
💡 Change the
DEPTH
constant to make a coarser or finer grained snowflake
You can also draw plants and trees using fractals:
Creating your own language
Forth also provides all the tools necessary to create your own language.
For example, if we want the Thurtle language to be more like Logo, we can define the TO
and END
keywords to replace the standard Forth words for starting and ending compilation:
You can even create a graphical language based on emoji: