Getting Started

Welcome to Xlerb! This guide will help you get up and running.

This guide will teach you Xlerb’s fundamentals - basic syntax and built-in words, how to define your own words and modules, how pattern matching and message passing works, and how to work with Elixir/Erlang functions.

Before we get too ahead of ourselves here: Concatenative/stack-based programming feels weird, and also, I am not an expert in it. I read Starting Forth, came down with a horrible cold and had fever dreams of sending messages to different stacks… and here we are.

It’s been fun to write, and maybe it’ll be fun to learn! If you’re an expert on this, particularly if you’re someone who’s programmed Forth professionally, please send me an email! I’d love to hear your feedback and where I’ve gotten things horribly wrong.

First steps

Anyway, let’s start off simple:

Fire up the Xlerb repl with

$ xlerb repl
0>

The prompt is waiting for you to do something with it. Try adding some numbers onto the stack:

xlerb[0]> 1 2 3
xlerb[3]>

Notice how we didn’t get any output, but the 0 turned to a 3. This shows us the current stack depth.

We can print out the contents of the stack (without affecting it) with .s:

xlerb[0]> 1 2 3
xlerb[3]> .s
3
2
1

The top of the stack is at the… top. Most words operate on the top of the stack, or at least the topmost ones.

. is a bit like .s, but it pops the top element and prints it out to the console:

xlerb[3]> .
3
xlerb[2]> 

Notice how the count went down. Indeed:

xlerb[2]> .s
2
1

Let’s do something a bit more interesting:

xlerb[2]> +
xlerb[1]> dup
xlerb[2]> .s
3
3
xlerb[2]> * .
9
xlerb[0]>

I’ll leave this one with you - you can probably guess what dup does. There’s also drop.

Try out pushing other numbers onto the stack, and other operators like * or -.

The key take-aways here are:

  • The stack is implicit, and always there
  • Words are all about doing things to the stack, like printing it out swapping elements around
  • Programs are just trains of words, one after another; you can take all of the things we typed: (1 2 3 .s . .s + dup .s * .), paste it into a line in the REPL, and get the same output!

Another note is that Starting Forth and other resources are going to provide a better introduction to this flavour of programming. I’d definitely pick that up and use as a reference if anything here doesn’t make sense.

Later sections of the guide will assume we all sort of ‘get’ what’s going on here with stacks etc, so make sure you’ve got your head around this whole concatenative business.