Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env stack
- -- stack runghc
- module Main where
- import Data.Functor (($>))
- import Data.Void (Void)
- import Text.Megaparsec ((<|>), Parsec, anySingle, atEnd, empty, eof, failure, label, lookAhead, many, runParser, takeP, try)
- import Text.Megaparsec.Char (char, newline, string)
- import Text.Megaparsec.Char.Lexer (decimal)
- -- Test:
- -- % echo -e 'xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))' | ./day03-mull-it-over.hs # = 161
- data Instruction = MulInstr Int Int deriving (Show)
- type Parser = Parsec Void String
- instrs :: Parser [Instruction]
- instrs = many instr <* eof
- mulinstr :: Parser Instruction
- mulinstr = string "mul(" *> (MulInstr <$> (decimal <* char ',') <*> (decimal <* char ')'))
- instr :: Parser Instruction
- instr = newline $> MulInstr 0 0
- <|> try mulinstr
- <|> anySingle *> instr
- -- How can this work? I don't want to match on newlines and insert dummy multiplications.
- -- But this yields a `TrivialError 72 (Just EndOfInput)`; how do I break out of the 'many' parser?
- instr' :: Parser Instruction
- instr' = try mulinstr
- <|> anySingle *> instr
- solve :: Either a [Instruction] -> Int
- solve (Right is) = sum [op1 * op2 | MulInstr op1 op2 <- is]
- main :: IO ()
- main = interact $ show . solve . runParser instrs "<stdin>"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement