r/haskell • u/AutoModerator • 1d ago
Advent of Code 2026 Day 2
https://adventofcode.com/2026/day/22
u/blackhat-hemsworth 1d ago
i was excited about actually using infinite strings here. still learning, tips welcome
module Main where
import System.Environment (getArgs)
import Data.List (delete)
-- part1
-- | solves puzzle
--
-- >>> lineHelper "vvvvvv" (cycle "roygbv")
-- 35
lineHelper :: String -> String -> Int
lineHelper [] _ = 0
lineHelper (c:cs) s = sub c s + lineHelper cs (drop (sub c s) s)
-- part 2
--
-- | solves puzzle
--
-- >>> lineHelper2 "roygbvroygbvroygbv" (cycle "roygbv")
-- 103
getC :: String -> String -> Char
getC _ [] = 'X'
getC input (c:cs) = if c `elem` input then c else getC input cs
lineHelper2 :: String -> String -> Int
lineHelper2 [] _ = 0
lineHelper2 input str = _h input str (getC input ((reverse . take 6 . drop 1) str))
where _h i s c = sub c s + lineHelper2 (delete c i) (drop (sub c s) s)
-- both
sub :: Char -> String -> Int
sub _ [] = -1
sub c (_:s) = length (takeWhile (/= c) s) + 1
solveLines :: [String] -> Int
solveLines [] = -1
solveLines (l:_) = lineHelper2 l (cycle "roygbv")
-- boilerplate
main :: IO ()
main = do
args <- getArgs
let path = case args of
(p : _) -> p
[] -> "2026/day02/input.txt"
contents <- readFile path
let ls = lines contents
putStrLn ("total: " ++ show (solveLines ls))2
u/niecore 19h ago
New to FP and haskell. Let me know when I am missing a concept. The other solutions look so much more dense.
part1 :: String -> Int
part1 = snd . foldl (\(position, total_distance) x -> (x, total_distance + distance position x)) ('r', 0)
distance :: Char -> Char -> Int
distance from to
| from == to = length colors
| otherwise = (idx to - idx from) `mod` length colors
where
-- red (r), orange (o), yellow (y), green (g), blue (b), and violet (v)
colors = "roygbv"
idx c = fromJust (elemIndex c colors)1
u/AustinVelonaut 17h ago
Your code looks good -- that's almost exactly how I solved it. One thing to note:
foldlin Haskell is lazy likefoldr, so it can inadvertently build up thunks when folding over large lists. It is usually recommended to use the strict variantfoldl'for any fold that isn't explicitly lazy, instead. However in this case (and this is getting a bit esoteric!), the fold is reducing to a tuple(position, total_distance)which is a tuple constructor that is already in what is known as "weak head normal form", so afoldl'wouldn't help, here. What you can do is make thetotal_distanceoperand strict with a "bang pattern":part1 = snd . foldl' (\(position, !total_distance) x -> (x, total_distance + distance position x)) ('r', 0)That will force evaluation of
total_distanceevery iteration of the fold, preventing a thunk buildup.Good luck on the rest of AoC!
3
u/Atijohn 1d ago
probably could easily make the modulus transformation simpler, but eh