mirror of
https://codeberg.org/JasterV/aoc2024-haskell.git
synced 2026-04-26 18:10:05 +00:00
refactor: Day1 to use mapM
This commit is contained in:
parent
566a92499a
commit
3035985d6b
1 changed files with 5 additions and 18 deletions
23
src/Day1.hs
23
src/Day1.hs
|
|
@ -4,6 +4,7 @@ module Day1
|
||||||
)
|
)
|
||||||
where
|
where
|
||||||
|
|
||||||
|
import Control.Monad (mapAndUnzipM)
|
||||||
import qualified Data.Bifunctor as BF
|
import qualified Data.Bifunctor as BF
|
||||||
import Data.Either
|
import Data.Either
|
||||||
import Data.List (sort)
|
import Data.List (sort)
|
||||||
|
|
@ -41,14 +42,7 @@ partTwo contents = calculateScore <$> BF.first ParseInputError (parseInput conte
|
||||||
count x = length . filter (== x)
|
count x = length . filter (== x)
|
||||||
|
|
||||||
parseInput :: String -> Either ParseError ([LocationID], [LocationID])
|
parseInput :: String -> Either ParseError ([LocationID], [LocationID])
|
||||||
parseInput xs =
|
parseInput xs = mapAndUnzipM (parseWords . words) (lines xs)
|
||||||
case errors of
|
|
||||||
[] -> Right parsedInput
|
|
||||||
(parseError : _) -> Left parseError
|
|
||||||
where
|
|
||||||
parse = map (parseWords . words) . lines
|
|
||||||
errors = lefts $ parse xs
|
|
||||||
parsedInput = unzip $ rights $ parse xs
|
|
||||||
|
|
||||||
parseWords :: [String] -> Either ParseError (LocationID, LocationID)
|
parseWords :: [String] -> Either ParseError (LocationID, LocationID)
|
||||||
parseWords [left, right] = do
|
parseWords [left, right] = do
|
||||||
|
|
@ -56,16 +50,9 @@ parseWords [left, right] = do
|
||||||
rightLocation <- parseRight
|
rightLocation <- parseRight
|
||||||
return (leftLocation, rightLocation)
|
return (leftLocation, rightLocation)
|
||||||
where
|
where
|
||||||
parseLeft =
|
parseLeft = BF.first (ParseLocationError left) (readEither left :: Either String LocationID)
|
||||||
BF.first
|
parseRight = BF.first (ParseLocationError right) (readEither right :: Either String LocationID)
|
||||||
(ParseLocationError left)
|
|
||||||
(readEither left :: Either String LocationID)
|
|
||||||
|
|
||||||
parseRight =
|
|
||||||
BF.first
|
|
||||||
(ParseLocationError right)
|
|
||||||
(readEither right :: Either String LocationID)
|
|
||||||
|
|
||||||
-- If the line does not contain exactly two words,
|
-- If the line does not contain exactly two words,
|
||||||
-- it is considered an error
|
-- it is considered an error
|
||||||
parseWords xs' = Left $ ParseLineError (unwords xs')
|
parseWords xs = Left $ ParseLineError (unwords xs)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue