Let’s make stacker, a programming language that acts as a stack-based calculator:
Our stacker language maintains a stack of arguments, which starts out empty. Each line of the program represents a new argument for the stack. If it’s a number, it’s simply pushed onto the top of the stack. But if it’s an operator—either + or *—then the top two arguments from the stack are popped off, and replaced with the result of applying the operator (meaning arg1 + arg2 or arg1 * arg2). So the sample program above means 3 * (8 + 4), and when it runs, the result is 36.
The stack is implemented with a list, the basic data structure of Racket. By convention, the top of our stack will correspond to the left side of a Racket list. Let’s visualize how the stack changes after each instruction, using the rules described above:
36 ; top value of (list 36)
Easy, right? If this seems like a weird way to do math, it’s called Reverse Polish Notation, and it has a long history in calculating machines.
Though stacker is simple, it will give us a gentle introduction to Racket, including a tour of its language-making workflow. Every language project will follow the same basic steps.
stacker will also get us thinking about the idea of a “little language” made for a specialized purpose—known as a domain-specific language or DSL. We can make general-purpose languages with Racket—and later on, we will. But languages don’t have to do everything. DSLs are valuable because they can be tailored to the problem at hand. And if you’ve programmed for a little while, it’s likely you’ve already used DSLs.
Some general programming experience is assumed.
No experience with Racket, Scheme, or Lisp is assumed.
Install Racket and the beautiful-racket package as described in Setup.
Make sure your Racket installation works by trying the sample below. Click the “copy to clipboard” icon in the upper-right corner of the code sample (the button will appear when you hover over the box):
Paste the code into the upper pane of a new DrRacket window (also known as the definitions area), entirely replacing anything that’s there (including a #lang line, if any):
Click Run, and the result should appear in the lower pane (also known as the interactions area or REPL):
Unlike this sample, most code samples in this book don’t have a #lang line at the top. They’re presumed to use the Beautiful Racket language, #lang br. This line will automatically appear at the top of every new DrRacket window if you configured it to do so. Otherwise (or if you’re not using DrRacket) you’ll need to add it yourself.
If the sample program worked, we can continue.