ninethehacker.xyz Fizzbuzz in Forth

Fizzbuzz in Forth

fizzbuzz in a classic SOPlang


Forth is an old language with a new lease on life. It was originally designed for high speed real time calculations close to bare metal. It’s a stack orientated language that uses reverse polish notation which is very alien when compared to c like languages I’m more familiar with.

Forth has a strong background in embedded software having been used in the firmware of iconic american jet fighters and research aircraft of the 80s. It has been ported to many modern commodity microcontrollers including Atmel AVR chips in Arduino compatibles and STM32 ARM Cortex chips.

More recently Forth has re-emerged to prominence as the basis for bitcoin and ethereum script. Both use subsets of common forth to implement smart contracts. Ehtherium uses a turing complete implementation including loop constructs. While bitcoin script does not include loop constructs turing completeness was proved for distributed calculations using automata theory. Essentially you can iterate over successive payments in the smart contracts. This makes the blockchain a distributed parallel processing supercomputer akin to OpenCL/cuda devices. I do not understand any of the math papers in regards to this but I am trying to so don’t hold your breath, but I may publish a deep dive into implementing smart contracts in the future.

getting started in forth

The quickest easiest way is probably GNU forth on linux. Install it with your relevant package manager and call it with gforth to jump into an interactive shell.

There are quite a few educational resources out there, here are some I found useful

fizzbuzz implementation

: fizzbuzz
    cr 16 1 do
        i 3 mod 0<> i 5 mod 0<> and if i . then
        i 3 mod 0= if ." fizz " then
        i 5 mod 0= if ." buzz " then cr
    loop ;

fizzbuzz

To test this code snippet on your own machine save it to fizzbuzz.fs and then pipe it into gforth over stdin with cat fizzbuzz.fs | gforth.

Getting to this point broke my brain. I’m very sure that there’s a way to implement this without a test on the default case. I still feel like I haven’t touched even a little of the language. I’m struck by the similarity to functional languages like lisp and haskell.


there are no comments yet


all comments are manually reviewed before publication