In jsonic, we saw how we could make a simple but useful DSL in under 50 lines of code. If anyone thought that creating a DSL was automatically a giant undertaking—Racket makes it easy.
In turn, when DSLs are easy to make, they become a practical option for solving a larger set of programming problems—even small ones. In this tutorial, we’ll take that principle to its extreme. We’ll make a language called wires that’s designed to be used once and discarded.
And let’s cleanse the rice-cake flavor of JSON from our palate with something more entertaining.
In 2015, programmer Eric Wastl created a terrific series of programming puzzles called Advent of Code. Though I recommend the whole set—and I’m looking forward to this year’s edition—Eric let me build this tutorial around my favorite puzzle from 2015, Some Assembly Required. The description below is by Eric.
This year, little Bobby Tables got a set of wires and bitwise logic gates! Unfortunately, little Bobby is under the recommended age range, and he needs help assembling the circuit.
Each wire has an identifier (some lowercase letters) and can carry a 16-bit signal (a number from 0 to 65535). A signal is provided to each wire by a gate, another wire, or some specific value. Each wire can only get a signal from one source, but can provide its signal to multiple destinations. A gate provides no signal until all of its inputs have a signal.
The included instruction booklet describes how to connect the parts:
123 -> x means that the signal 123 is provided to wire x.
x AND y -> z means that the bitwise AND of wire x and wire y is provided to wire z.
p LSHIFT 2 -> q means that the value from wire p is left-shifted by 2 and then provided to wire q.
NOT e -> f means that the bitwise complement of the value from wire e is provided to wire f.
Other possible gates include OR (bitwise OR) and RSHIFT (right-shift).
For example, here’s a simple circuit:
1 2 3 4 5 6 7 8
x AND y -> d x OR y -> e x LSHIFT 2 -> f y RSHIFT 2 -> g NOT x -> h NOT y -> i 123 -> x 456 -> y
After it’s run, these are the signals on the wires:
1 2 3 4 5 6 7 8
d: 72 e: 507 f: 492 g: 114 h: 65412 i: 65079 x: 123 y: 456
The instruction booklet for the circuit kit provides a description of a circuit (which will be our puzzle input).
We have to determine: What signal ends up on wire a?
Of course, we’re going to answer this question by making a DSL called wires.