Created
December 6, 2020 17:03
-
-
Save ollimandoliini/642319b058151018de611f0a0a1b0252 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
module Main where | |
-- DAY 4 | |
import Control.Applicative hiding (some, many) | |
import Control.Monad | |
import Data.Void | |
import Text.Megaparsec hiding (State) | |
import Text.Megaparsec.Char | |
import qualified Text.Megaparsec.Char.Lexer as L | |
requiredFields = [ | |
"byr", | |
"iyr", | |
"eyr", | |
"hgt", | |
"hcl", | |
"ecl", | |
"pid"] | |
type Parser = Parsec Void String | |
type Passport = [(String, String)] | |
main = do | |
fileContent <- readFile "day4.txt" | |
let result = numOfValidPassports $ parseMaybe (many passport) fileContent | |
print result | |
numOfValidPassports :: Maybe [Passport] -> Int | |
numOfValidPassports Nothing = 0 | |
numOfValidPassports (Just pps) = sum $ map fromEnum $ map isValid pps | |
isValid :: Passport -> Bool | |
isValid passport = | |
all (\x -> x `elem` fields) requiredFields | |
where | |
fields = fmap fst passport | |
section :: Parser (String, String) | |
section = do | |
field <- some letterChar | |
void $ char ':' | |
value <- some (alphaNumChar <|> char '#') | |
void spaceChar <|> eof | |
return (field, value) | |
passport :: Parser Passport | |
passport = do | |
content <- some section | |
(void $ char '\n') <|> eof | |
return content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment