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,39 +2,58 @@ 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
traverse
( \case runPuzzle :: Puzzle a -> IO ()
'L' : (readMaybe -> Just i) -> Just (L, Inc i) runPuzzle p = do
'R' : (readMaybe -> Just i) -> Just (R, Inc i) Just input <- p.parse <$> readFile ("inputs/examples/" <> show p.number)
_ -> Nothing putStrLn $ p.part1 input
) putStrLn $ p.part2 input
. lines data Puzzle input = Puzzle
<$> readFile "inputs/examples/1" { number :: Word
print , parse :: String -> Maybe input
. sum , part1 :: input -> String
. flip evalState 50 , part2 :: input -> String
$ for input \(d, i) -> state \p -> }
let (_, p') = step i d p
in (Count if p' == 0 then 1 else 0, p') puzzle1 :: Puzzle [(Direction, Inc)]
print puzzle1 =
. sum Puzzle
. flip evalState 50 { number = 1
$ for input \(d, i) -> state \p -> , parse =
let (c, p') = step i d p traverse
c' = case d of ( \case
R -> abs c 'L' : (readMaybe -> Just i) -> Just (L, Inc i)
L -> 'R' : (readMaybe -> Just i) -> Just (R, Inc i)
if _ -> Nothing
| p == 0 -> abs c - 1 )
| p' == 0 -> abs c + 1 . lines
| otherwise -> abs c , part1 =
in (c', p') show
. sum
. flip evalState 50
. traverse \(d, i) -> state \p ->
let (_, p') = step i d p
in (Count if p' == 0 then 1 else 0, p')
, part2 =
show
. sum
. flip evalState 50
. traverse \(d, i) -> state \p ->
let (c, p') = step i d p
c' = case d of
R -> abs c
L ->
if
| p == 0 -> abs c - 1
| p' == 0 -> abs c + 1
| otherwise -> abs c
in (c', p')
}
data Direction = L | R data Direction = L | R
deriving (Eq, Ord, Show) deriving (Eq, Ord, Show)