Getting Ready to do Advent of Code with Gleam
I'm counting down the day's until 2024's Advent of Code, an annual coding challenge that I like to use for trying out new tools or techniques. It poses 25 challenges, one a day from December 1st to December 25th, each of which involves parsing a bunch of data and then answering two algorithmic questions about it. I've never finished the set (especially since I became a dad), but I usually learn something and always enjoy myself.
This year I'm planning to use the Gleam programming language for my attempt. Gleam is quite a new language compared to something like Python or Rust and has a few quirks that can complicate the sort of ad-hoc problems solving that AoC demands. To make sure I can focus on the coding problems instead of fighting my tools, I solved a few challenges from 2023 as a way to prepare. Here are some of the things I learned.
Use a fresh install
If you have an older version of Gleam installed it can cause some very strange problems with unhelpful error messages, so if you don't have a working environment I recommend starting fresh.
You can find the instructions for installation here.
Setting up a "project" and running code and tests
Gleam code runs inside a "project", which we want anyways so that we can use packages. You can create a project with
gleam new <projectname>
Once you've set it up, you create modules in the src
directory. You can run the file src/foo/bar/baz.gleam
with
gleam run -t erlang -m foo/bar/baz
The standard library is a package
Unlike some languages, the gleam standard library is it's own package. You'll probably want to familiarize yourself with modules like list
, dict
, string
, and io
. You can install it with
gleam add gleam_stdlib
Error handling (or avoidance thereof)
One of gleam's selling points is its excellent error handling. This is very helpful for programs where you want to handle errors, but many Advent of Code programs will only every run on one puzzle input: yours! Sometimes it's totally appropriate to crash if some Result
isn't Ok
.
Enter let assert
, Gleam's escape hatch for exactly this case!
// This binds the value "foo" to x
let assert Ok(x) = Ok("foo")
// This panics
let assert Ok(y) = Error(Nil)
You may want to do propper error handling for one or two problems just to get the hang of it, but I think it's totally fine to use let assert
in this context so you can focus on solving the actual challenge.
Other helpful packages
Many Advent of Code challenges require you to load a big input string. You could put it in a const
, but there's a package called simplifile that makes it, well, simple to load data from a file!
import simplifile
pub fn main() {
let assert Ok(source) = simplifile.read("path/to/your/inputfile")
todo
}
Some packages are also extremely amenable to regular expressions. These are in their own package, not the standard library.