Let’s make stacker, a programming language that acts as a stack-based calculator:
Our stacker language maintains a of , 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 this sample program means 3 * (8 + 4), and when it runs, the result is:
The stack is implemented with a , 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 or . 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. Paste the code into the top pane of a new DrRacket window, entirely replacing anything that’s there. Click Run.
The result should be:
Most code samples in this book don’t already 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.