From 832c62bef4886b6411d939ec8cd0ba0632f14bfb Mon Sep 17 00:00:00 2001 From: Quinten Kock Date: Sat, 11 Dec 2021 19:24:56 +0100 Subject: [PATCH] day10: cleanup - use elem instad of a massive chain of || - add explicit error cases --- 2021/day10.hs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/2021/day10.hs b/2021/day10.hs index 5d1763e..5719650 100644 --- a/2021/day10.hs +++ b/2021/day10.hs @@ -2,18 +2,21 @@ module Day10 where import Data.Maybe import Data.List (sort) +import Control.Monad (foldM) + closing :: Char -> Char closing '(' = ')' closing '[' = ']' closing '{' = '}' closing '<' = '>' +closing _ = error "Not a bracket" -score :: Char -> Int -score ' ' = 0 -score ')' = 3 -score ']' = 57 -score '}' = 1197 -score '>' = 25137 +score :: Char -> Maybe Int +score ')' = Just 3 +score ']' = Just 57 +score '}' = Just 1197 +score '>' = Just 25137 +score _ = Nothing closingScore :: Char -> Int closingScore ')' = 1 @@ -28,13 +31,13 @@ calcScore xs = foldr (\char score -> score*5 + closingScore char) 0 (reverse xs) getInvalidChar :: [Char] -> String -> Char getInvalidChar _ [] = ' ' getInvalidChar st (x:xs) - | x == '(' || x == '[' || x == '{' || x == '<' = getInvalidChar (x:st) xs + | x `elem` "([{<" = getInvalidChar (x:st) xs | otherwise = if Just x == fmap closing (listToMaybe st) then getInvalidChar (tail st) xs else x getCompletionString :: [Char] -> String -> String getCompletionString st [] = map closing st getCompletionString st (x:xs) - | x == '(' || x == '[' || x == '{' || x == '<' = getCompletionString (x:st) xs + | x `elem` "([{<" = getCompletionString (x:st) xs | otherwise = if Just x == fmap closing (listToMaybe st) then getCompletionString (tail st) xs else "" @@ -43,7 +46,7 @@ main = do input <- lines <$> getContents putStr "part 1: " - let chars = map (score . getInvalidChar []) input + let chars = mapMaybe (score . getInvalidChar []) input print $ sum chars putStr "part 2: "