Day 2 down. Today's problem was a modular arithmetic problem. A "program" is a list of positions on a repeating tape that we have to calculate the offsets of and sum up.

I used recursion today. Gleam doesn't have for or while loops. Instead, like many other functional languages, it expects all looping to happen via recursion and implements the tail-call optimization to support this. run_program() is implemented via a recursive helper run_program_inner() which takes the current position and total distance as additional arguments.

I also wrote my first generic function today. I was expecting some separate syntax for defining generic type parameters, but it turns out that functions are default generic in Gleam. You simply use type names with lowercase letters, and they become generic types.

Something that surprised me coming from Rust; no panicking unwrap(). I'm used to quickly prototyping code with unwrap() and failing the program if any of my expectations are unmet. Gleam has a result.unwrap() function, but it takes a default value to fill in if the Result is Error. I wrote an expect() function which fits nicely into pipelines and opened an issue asking whether it could be in the standard library.

import gleam/int
import gleam/list
import gleam/order
import gleam/string

import simplifile

pub fn main() -> Nil {
  echo run_program(day02_input())
  echo run_program(sort_program(day02_input()))

  Nil
}

fn day02_input() -> String {
  simplifile.read("inputs/day02.txt")
  |> expect("could not read input")
  |> string.trim()
}

fn expect(r: Result(a, b), message: String) -> a {
  case r {
    Ok(a) -> a
    Error(_) -> panic as message
  }
}

fn sort_program(program: String) -> String {
  program
  |> string.to_graphemes()
  |> list.sort(fn(x, y) {
    let f = fn(x) {
      x
      |> position_as_int()
      |> int.subtract(1)
      |> int.modulo(6)
      |> expect("outside range")
    }
    order.negate(int.compare(f(x), f(y)))
  })
  |> list.fold("", string.append)
}

/// Runs `program` and returns how far it jumped.
fn run_program(program: String) -> Int {
  run_program_inner(program, "r", 0)
}

fn run_program_inner(program: String, position: String, distance: Int) -> Int {
  case string.pop_grapheme(program) {
    Ok(#(target, rest)) ->
      run_program_inner(rest, target, distance + jump(position, target))
    Error(Nil) -> distance
  }
}

fn jump(curr: String, target: String) -> Int {
  int.modulo(position_as_int(target) - position_as_int(curr), 6)
  |> expect("outside range")
  |> fn(x) {
    case x {
      0 -> 6
      x -> x
    }
  }
}

fn position_as_int(pos: String) -> Int {
  case pos {
    "r" -> 0
    "o" -> 1
    "y" -> 2
    "g" -> 3
    "b" -> 4
    "v" -> 5
    _ -> panic
  }
}