Created
December 1, 2023 21:45
-
-
Save Alwinfy/2729b3536cf7d566209bf18c282756b3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Applicative ((<|>), Alternative) | |
import Control.Arrow ((&&&)) | |
import Control.Monad (guard) | |
import Data.Bifunctor (bimap) | |
import Data.Char (digitToInt, isDigit) | |
import Data.List (findIndex, tails, isPrefixOf) | |
import Data.Maybe (catMaybes, listToMaybe) | |
parse :: Alternative f => Char -> f Int | |
parse s = guard (isDigit s) *> pure (digitToInt s) | |
numbers :: [String] | |
numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] | |
parse2 :: String -> Maybe Int | |
parse2 t = (listToMaybe t >>= parse) <|> (1+) <$> findIndex (`isPrefixOf` t) numbers | |
main :: IO () | |
main = ((bimap >>= id) (sum . map (extract . catMaybes)) . (map (map parse) &&& map (map parse2 . tails)) . lines <$> getContents) >>= print | |
where extract ls = 10 * head ls + last ls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment