I like to choose a new language to learn for Advent of Code each year. This year, I thought I would give Gleam a try. Gleam is a functional, strongly-typed language with Rust-like syntax that runs on the BEAM (Erlang) VM. It's been on my list for a little while.

Day 1 of Advent of Code is all about getting set up. Installing Gleam was easy (it was in my package manager's repos). Starting a new project was easy (the gleam tool has gleam new and gleam add for dependencies, similar to cargo). I'm not yet sure how I will structure this repo so that every day can coexist. For now, I just have my solution in the default file that gleam add created.

Today's problem is a top $k$/bottom $k$ problem. The input is a list of integers and the desired output is the product of the three most common (part 1) or least common (part 2) integers.

Here are some things I like about Gleam so far:

  • Rust-like syntax: It was fairly intuitive for me to get started as a Rust programmer. I had the language guide open to the side and occasionally looked at sample code to see how to do things. Types are written almost the same way (generic types are written with parenthesis instead of angle brackets, but everything else seems the same). Option and Result exist.

  • Pipeline operator: |> is great for functionally performing a sequence of transformations on a value.

  • Free functions in modules: For example, string.trim() is a free function in the string module. It's first parameter is the string to trim. This pairs very nicely with the pipeline operator, which inserts the current pipeline value as the first argument of the called function. Thus, trimming a string can be done in the following two ways:

    // As a normal function call
    string.trim(s)
    
    // In a pipeline
    s
    |> string.trim()

    I'm enjoying free functions in modules because string.trim() explicitly names the trim() function that works with strings (rather than any other trim function that might exist). This is something I don't think about much in Rust because of type inference, but I'm kind of liking how this feels too.

Here are some things that were surprising for me about Gleam:

  • Barebones standard library: No file I/O in the standard library; I had to pull in a dependency (simplifile) to read the input.
  • Difficult to find debug printing: It took me some time to find the echo keyword. There doesn't seem to be much (or any) string formatting in the standard library.

More on this later. Here's my Day 1 solution in its entirety.

import gleam/dict.{type Dict}
import gleam/int
import gleam/list
import gleam/option.{None, Some}
import gleam/order
import gleam/string

import simplifile

pub fn main() -> Nil {
  let input = day01_input()

  top_k(input, 3)
  |> list.fold(1, int.multiply)
  |> echo

  bot_k(input, 3)
  |> list.fold(1, int.multiply)
  |> echo

  Nil
}

fn day01_input() -> List(Int) {
  let assert Ok(s) = simplifile.read("inputs/day01.txt")

  s
  |> string.trim()
  |> string.split("\n")
  |> list.map(fn(s) {
    let assert Ok(x) = int.parse(string.trim(s))
    x
  })
}

type Side {
  Top
  Bottom
}

/// Return the top `k` numbers from `xs` by frequency.
fn top_k(xs: List(Int), k: Int) {
  choose_k(xs, k, Top)
}

/// Return the bottom `k` numbers from `xs` by frequency.
fn bot_k(xs: List(Int), k: Int) {
  choose_k(xs, k, Bottom)
}

fn choose_k(xs: List(Int), k: Int, side: Side) -> List(Int) {
  let order_op = case side {
    Top -> order.negate
    Bottom -> fn(x) { x }
  }

  count_occurrences(xs)
  |> dict.to_list()
  |> list.sort(fn(x: #(Int, Int), y: #(Int, Int)) {
    let #(_, x_occurrences) = x
    let #(_, y_occurrences) = y

    int.compare(x_occurrences, y_occurrences) |> order_op()
  })
  |> list.map(fn(x: #(Int, Int)) {
    let #(x, _) = x

    x
  })
  |> list.take(k)
}

/// Return a `Dict` where the keys are the integers in the input list and the
/// values are the number of times that integer occurs in the list.
fn count_occurrences(xs: List(Int)) -> Dict(Int, Int) {
  let increment = fn(x) {
    case x {
      Some(i) -> i + 1
      None -> 1
    }
  }

  xs
  |> list.fold(dict.new(), fn(d, x) { dict.upsert(d, x, increment) })
}