Refactor to make things more reusable

This commit is contained in:
George Thomas 2025-12-02 02:01:37 +00:00
parent 0efd99220e
commit b9e69eb983
2 changed files with 51 additions and 29 deletions

View File

@ -11,7 +11,10 @@ executable aoc
default-language: GHC2024 default-language: GHC2024
default-extensions: default-extensions:
BlockArguments BlockArguments
DuplicateRecordFields
MultiWayIf MultiWayIf
NoFieldSelectors
OverloadedRecordDot
ViewPatterns ViewPatterns
ghc-options: ghc-options:
-Wall -Wall

View File

@ -2,12 +2,29 @@ module Main (main) where
import Control.Monad.State import Control.Monad.State
import Data.Bifunctor import Data.Bifunctor
import Data.Traversable
import Text.Read (readMaybe) import Text.Read (readMaybe)
main :: IO () main :: IO ()
main = do main = do
Just input <- runPuzzle puzzle1
runPuzzle :: Puzzle a -> IO ()
runPuzzle p = do
Just input <- p.parse <$> readFile ("inputs/examples/" <> show p.number)
putStrLn $ p.part1 input
putStrLn $ p.part2 input
data Puzzle input = Puzzle
{ number :: Word
, parse :: String -> Maybe input
, part1 :: input -> String
, part2 :: input -> String
}
puzzle1 :: Puzzle [(Direction, Inc)]
puzzle1 =
Puzzle
{ number = 1
, parse =
traverse traverse
( \case ( \case
'L' : (readMaybe -> Just i) -> Just (L, Inc i) 'L' : (readMaybe -> Just i) -> Just (L, Inc i)
@ -15,17 +32,18 @@ main = do
_ -> Nothing _ -> Nothing
) )
. lines . lines
<$> readFile "inputs/examples/1" , part1 =
print show
. sum . sum
. flip evalState 50 . flip evalState 50
$ for input \(d, i) -> state \p -> . traverse \(d, i) -> state \p ->
let (_, p') = step i d p let (_, p') = step i d p
in (Count if p' == 0 then 1 else 0, p') in (Count if p' == 0 then 1 else 0, p')
print , part2 =
show
. sum . sum
. flip evalState 50 . flip evalState 50
$ for input \(d, i) -> state \p -> . traverse \(d, i) -> state \p ->
let (c, p') = step i d p let (c, p') = step i d p
c' = case d of c' = case d of
R -> abs c R -> abs c
@ -35,6 +53,7 @@ main = do
| p' == 0 -> abs c + 1 | p' == 0 -> abs c + 1
| otherwise -> abs c | otherwise -> abs c
in (c', p') in (c', p')
}
data Direction = L | R data Direction = L | R
deriving (Eq, Ord, Show) deriving (Eq, Ord, Show)