Advent of Code 2026Part 1
Advent of Code 2026 has arrived!
Solving day 1 in Haskell
Part 1
Advent of Code 2026 is here, and as usual day 1 is a gentle start. The puzzle boils down to this: given a list of IDs, find the three most common ones and multiply them together.
First, the imports. Nothing unusual, but if you’re new to Haskell a few of these might look unfamiliar, so here’s a quick tour.
The “and then” family of functions
(&) = flip ($) lets you write [1, 2, 3] & map (* 2) & sum, so data flows left to right,
instead of the more common sum $ map (* 2) [1, 2, 3].
(>>>) = flip (.) does the same for composition: map (* 2) >>> sum instead of sum . map (* 2).
(<&>) = flip (<$>) does the same for functors: readFile path <&> (lines >>> length)
instead of length . lines <$> readFile path.
{-# LANGUAGE TypeApplications #-}
module Day01 (parse, part1, part2) where
import System.IO (readFile')
import qualified Data.HashMap.Strict as Map
import Data.Hashable (Hashable)
import Data.Function ((&))
import Data.List (sortOn)
import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Ord (Down(Down))
import Data.HashMap.Strict (HashMap)I always start by defining the Input type.
type Input = [Int]And a function to parse it.
parse :: String -> Input
parse = lines >>> map (read @Int)Since we’re counting IDs, let’s write a small helper, frequencies, that builds a HashMap
from each ID to how often it appears.
We fold over the list, and Map.insertWith (+) n 1 either inserts 1 for a new ID
or adds 1 to its existing count.
frequencies :: (Hashable a) => [a] -> HashMap a Int
frequencies = foldl' insertID Map.empty
where
insertID acc n = Map.insertWith (+) n 1 accWith the counts in hand, the rest is a pipeline: turn the map into a list of (ID, count) pairs,
sort by count from highest to lowest (that’s what Down is for), take the top 3,
keep just the IDs, and multiply them.
This is where the “and then” operators come in handy.
part1 :: Input -> Int
part1 nums =
frequencies nums
& Map.toList
& sortOn (Down . snd)
& take 3
& map fst
& product All that’s left is the impure part: read the input file, then use <&>
to run parse >>> part1 on its contents.
runPart1 :: IO Int
runPart1 = readFile' "./assets/day01-input.txt"
<&> (parse >>> part1)Part 2
Now we want the three least common IDs. It’s the same pipeline as part1,
just without Down, so the counts sort from lowest to highest.
part2 :: Input -> Int
part2 nums =
frequencies nums
& Map.toList
& sortOn snd
& take 3
& map fst
& product
runPart2 :: IO Int
runPart2 = readFile' "./assets/day01-input.txt"
<&> (parse >>> part2)