Lambda Discipline

Examples

Advent of Code 2024, day 1, part 2

examples/aoc-24/day-01/part_02.lbd

-- Problem: https://adventofcode.com/2024/day/1 (part two)
-- Run from anywhere: lbd run examples/aoc-24/day-01/part_02.lbd

use "../../std.lbd"

-- The input is known to be well formed, so a parse error may stop the
-- program: `unwrapOk` takes the number out of `parseInt`'s `Result`.
parseLine : String -> List<Int> = \line. (map \word. (unwrapOk (parseInt word)) (split "   " line))

-- The puzzle is a pure function of the input text.
similarity : String -> Int = \input.
    let columns = (transpose (map parseLine (lines input))) in
    let left = (unwrap (get 0 columns)) in
    let right = (unwrap (get 1 columns)) in
    (sum (map \x. (mul x (count (eq x) right)) left))

-- Reading the input is an action; `<-` names its result. `__DIR__` is
-- this file's directory, so the input is found from any working directory.
let input <- (readFile (concat __DIR__ "/input.txt")) in
(println (concat "Answer: " (show (similarity input))))

Output

Answer: 21070419

Run it yourself from the repository root: lbd run examples/aoc-24/day-01/part_02.lbd