module Day1 import System import System.File import Data.String import Text.Parser parsePair : String -> Maybe (Int, Int) parsePair pair = do num1 <- parseInteger (fst p1) num2 <- parseInteger (snd p2) pure (num1, num2) where p1 = span (/= ' ') pair p2 = span (== ' ') (snd p1) parseStr : String -> List (Int, Int) parseStr str = do nums <- lines str maybe [] pure (parsePair nums) transposePairs : List (a, b) -> (List a, List b) transposePairs ls = (map fst ls, map snd ls) part1 : (List Int, List Int) -> Int part1 inp = sum $ zipWith (\x => \y => abs (x - y)) (sort $ fst inp) (sort $ snd inp) occur : Eq a => Num b => a -> List a -> b occur x fs = foldr (\y => \r => if x == y then r + 1 else r) 0 fs part2 : (List Int, List Int) -> Int part2 (l1, l2) = sum $ map (\x => x * (occur x l2)) l1 main : IO () main = do estr <- readFile "data/day1.txt" str <- either (die . show) pure estr putStrLn $ show $ part1 $ transposePairs $ parseStr str putStrLn $ show $ part2 $ transposePairs $ parseStr str